Store variable inside function

Hello.

How can I store the “current i” inside each onclick function?

for(var i = 0; i < document.getElementsByClassName('gap').length; i++ ) {

	document.getElementsByClassName('gap')[i].onclick = function() { 
		alert(i);
}
}

I tried this, This returns the last “i” on every element. Why are this happening? Are the functions not local here?

Best regards

The scope of the var declaration is not just the for block but the current execution context, so all callback functions hold a reference to that same variable, ending up with the value after the last increment. To avoid this, you can either use let instead of var as let is indeed block scoped, or better yet, use forEach():

document.querySelectorAll('.gap').forEach(function (gap, index) {
  gap.addEventListener('click', function () {
    alert(index)
  })
})
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.