Jquery variables not working

I have some code that makes the background color of a div fade. The code currently works the way I want, but I would like to replace part of its variable so that I can change which div (s) it will affect. The div that it affects has the identifier "one", but when I try to make it a variable value and bind the variable in the code placed in it, it no longer works. Is there any other way to do this for it to work? Here is the code:

var temp2 = "one";
$(document).ready(function () {
    $("#temp2").click(function () {
        $("#temp2").animate({
            "opacity": "0.15"
        }, "slow");
    });
});
+5
source share
1 answer

You are close ... try this.

var temp2 = "#one";
$(document).ready(function () {
    $(temp2).click(function () {
        $(this).animate({
            opacity: '0.15'
        },
            "slow");
    });
});

here is a working example

Alternatively, you can simply use the class and forget about the variable.

$(document).ready(function () {
    $('.animateMe').click(function () {
        $(this).animate({
            opacity: '0.15'
        },
            "slow");
    });
});

See this working example.

"id", ,

var arr = ["one", "two", "three", "four", "five"];
$(document).ready(function () {
    // loop through the array
    jQuery.each(arr, function () {
        // create a local variable
        var id = '#' + this;
        $(id).click(function () {
            $(id).animate({
                opacity: '0.15'
            },
                "slow");
        });
    });
});

+7

All Articles