I have some code that makes the background color of a div fade. The code is currently working the way I want it to, but I would like to replace part of it with a variable so I can change which div(s) it will affect. The div that it is affecting has an id of "one", but when I try to make that the value of a variable and stick the variable in the code in it's placed, it doesn't work anymore. Is there a different way I can do this to make it work? Here is the code:
var temp2 = "one";
$(document).ready(function () {
    $("#temp2").click(function () {
        $("#temp2").animate({
            "opacity": "0.15"
        }, "slow");
    });
});
                Declare a variable using the var keyword. Initialize using the = symbol. Example: var hText = "This is just some text." - Click on the heading to see the text displayed in the <p> elements.
JavaScript (jQuery) variable will have only two scopes. Global Variables − A global variable has global scope which means it is defined everywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined.
The jQuery global variable is a variable that is declared outside a function and which can be accessed from any function. The variable declared outside a function becomes a global variable and it gets the global scope, which means that the variable can be accessed in all the scripts and functions on a page.
You're close... try this.
var temp2 = "#one";
$(document).ready(function () {
    $(temp2).click(function () {
        $(this).animate({
            opacity: '0.15'
        },
            "slow");
    });
});
here's a working example
Alternatively, you can just use a class and forget about the variable.
$(document).ready(function () {
    $('.animateMe').click(function () {
        $(this).animate({
            opacity: '0.15'
        },
            "slow");
    });
});
Please see this working example
also, you can create an array of "id's" if you want the same handler to run on multiple elements
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");
        });
    });
});
here's a working example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With