0

I have the following code:

<div id="0">click here</div>
<div id="1">click here</div>
<div id="2">click here</div>

for(var i=0;i<3;i++){

   document.getElementById(i).addEventListener("click",function(){
      alert(i);
   });

}

How can I get my callback function to alert 1, then 2 and then 3? It always alerts 3, and I need a way for it to save the value of 'i' at each iteration.

  • what value do you want to save? can you said me? – Enrique YC Aug 06 '15 at 20:32
  • Hello there User1306470 Basically the `=` symbol in Javascript doesn't copy the value across it creates a reference, so basically what you are doing above in your code is setting the alert to i, which is a reference to the var i in your for loop, which in the end is 3 so, I have created a jsFiddle which should help you out :) jsFiddle : https://jsfiddle.net/mo7vg43L/ – Canvas Aug 06 '15 at 20:35
  • I understand... so is there a way of copying the value instead of just the reference? The problem with you code is that 'this' doesn't have the information that I want my event listener to save. – user1306470 Aug 06 '15 at 20:43

2 Answers2

0

A global counter variable can be used to count the number of clicks.

var counter = 1;
for(var i=0;i<3;i++){
   document.getElementById(i).addEventListener("click",function(){
      alert(counter++);
   });
}
  • That wouldn't work for me because I need to change the value of counter outside the callback – user1306470 Aug 06 '15 at 20:39
  • Thank you for posting an answer to this question! Code-only answers are discouraged on Stack Overflow, because a code dump with no context doesn't explain how or why the solution will work, making it difficult for the original poster (or any future readers) to understand the logic behind it. Please, edit your question and include an explanation of your code so that others can benefit from your answer. Thanks! – Maximillian Laumeister Aug 06 '15 at 22:39
0
for(var i=0;i<3;i++) {
    document.getElementById(i).addEventListener("click", (function() {
            var j = i;
            return function() {
                alert(j);
            }
        })();
    );
}

Also this one should work:

for(var i=0;i<3;i++) {
    document.getElementById(i).addEventListener("click", (function(j) { alert(j); }).bind(undefined,i));
}
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
skypjack
  • 49,335
  • 19
  • 95
  • 187