multiple ids affected when i only want to change one (javascript & jquery)

Go To StackoverFlow.com

0

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);
        };
    });
});

};

2012-04-05 00:28
by ben
Can you post your HTML. You may have duplicate elements that are matching your selector criteria - Michael Rice 2012-04-05 00:29
This isn't the problem, but note that $(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 should not add handlers inside a handler. Your click handler creates a key up. That's bad - AutoSponge 2012-04-05 00:33


2

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.

2012-04-05 00:35
by AlienWebguy
Thanks for the tip, but that didn't quite do it - ben 2012-04-05 00:42
Are you certain? Without a fiddle or anything, I'm sticking with my answer, heh - AlienWebguy 2012-04-05 00:45
It looks like when I swap your bit in, the function becomes unable to define 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
It should work if the box indeed has an input inside it. If not, then you're making some bold assumptions with class responsibilities - AlienWebguy 2012-04-05 02:39
Ads