Jean-Paul Bardou
Jean-Paul Bardou

Reputation: 117

Jquery Create "array" of .click functions

I have a set of divs:

<div id="div_01">ASD</div>
<div id="div_02">ASD</div>
<div id="div_03">ASD</div>

I want to create a set of .click functions for those divs:

I tried this:

    for (var i = 1; i < 4; i++) {
        var picName = "#BSViolenceDiv_0" + i.toString();
        //alert("\nI have for i: " + i + ": " + picName);
        $("#div_0" + i.toString()).click(function(){
             $("#div_0" + i.toString()).animate({opacity:1}, 1000);
         });    
    }

It does not work because i ends up being 3.

What did I do wrong?

Upvotes: 1

Views: 418

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

It'll be better if you could use a global class instead (e.g my_div) like:

<div id="div_01" class="my_div">ASD</div>
<div id="div_02" class="my_div">ASD</div>
<div id="div_03" class="my_div">ASD</div>

Then attach click event to this class so you don't need to loop through all the div's :

$(".my_div").click(function(){
    $(this).animate({opacity:1}, 1000); // "$(this)" refer to the clicked div
})

Hope this helps.

$(".my_div").click(function(){
  $(this).animate({opacity:1}, 1000);
})
.my_div{
  opacity: 0.3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div_01" class="my_div">ASD</div>
<div id="div_02" class="my_div">ASD</div>
<div id="div_03" class="my_div">ASD</div>

Upvotes: 2

trincot
trincot

Reputation: 350137

The variable i has reached its final value before the code in the click event handler is executed, so it will always use that final value in the click handler, and as a consequence the selector "#div_0" + i.toString() will not refer to the element clicked on.

But you don't really need i to refer to the clicked element. Just use this:

Replace:

$("#div_0" + i.toString()).animate

with:

$(this).animate

That is the essence of your error. But as others have stated you don't need to create a separate handler for each div. Just create one for all, for instance by creating a class for them, and use that to select the div elements.

Upvotes: 1

Related Questions