Elan Posted August 11, 2019 Share Posted August 11, 2019 Why does this not work? var i; for (i = 0; i <= correctEls.length; i++) { correctEls[j].addEventListener("click", function() { whenCorrectClicked(i); }); i++; } Here is the full site for more info https://jsfiddle.net/elan5000/v7obgfny/256/ Link to comment Share on other sites More sharing options...
justsomeguy Posted August 12, 2019 Share Posted August 12, 2019 Because by the time that event handler runs, i is set to something else. It doesn't use the value that i had when you assigned the event handler, it uses the current value of i, whatever that is. You can use a closure to pass i as a new variable and use the value of that instead. var i; for (i = 0; i <= correctEls.length; i++) { correctEls[j].addEventListener("click", (function(idx) { return function() { whenCorrectClicked(idx); } })(i)); i++; } Now that makes an anonymous function that executes immediately (IIFE), which you pass the value of i, and inside the function it uses idx for the parameter. The IIFE returns a function which uses the value of idx, that returned function gets assigned as the click handler. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now