I have a number of .box
elements within a .color_container
. I've written this function so that when I click on one of those boxes, I am able to change its background color. This works fine with one box, but when I click on another and change its color, all other boxes I've clicked on are affected too.
I would only like to change the color of the box that I have just clicked on. Here is my code. Many thanks in advance for any help with this.
function defineColor(){
$(".color_container .box").click(function(){
var boxToModify = $(this);
if( $(this) .hasClass("plus") ){
$(this) .css("background-color", "rgb(255, 255, 255)")
.removeClass("plus")
.contents().remove();
};
var rgb = $(this).css("background-color").match(/\d{1,3}/g);
$("#box_r input").val(rgb[0]);
$("#box_g input").val(rgb[1]);
$("#box_b input").val(rgb[2]);
$(".box input").keyup(function(event){
var value = $(this).val();
if(value > 255 || isNaN(value) ){
alert("Error! Input must be a number 255 or less.");
}else if( value >= 0 && value <=255){
var r = $("#box_r input").val();
var g = $("#box_g input").val();
var b = $("#box_b input").val();
var output = "rgb(" + r + ", " + g +", " + b + ")";
$(boxToModify).css("background-color", output);
};
});
});
};
$(boxToModify)
is unnecessary as boxToModify
is already a jQuery object (third line of code). So, you can just do boxToModify.css(...
Chris Laplante 2012-04-05 00:31
You might want to change this:
$(".box input").keyup(function(event){
to this:
$(this).find('input').off('keyup').on('keyup', function(event) {
You're binding a keyup event to all boxes with that class on each click of a single box.
value
or something because it no longer modifies the background color of any of the boxes. I'm kind of new to this (as i'm sure you can tell from my code) - ben 2012-04-05 00:51