ZenKurd ZenKurd - 4 months ago 16
Javascript Question

event handler not working properly in loop

I am trying to apply some classes to html elements via foor loop. The problem is that the loop variable doesn't work correctly.



'use strict'

window.onload = function(){
var elements = document.getElementsByTagName("div")

for(var i = 0; i < elements.length; i++){
elements[i].addEventListener("click", a(this, i), false)
}

function a(e, x){
if(!e.className){
e.className = "class".concat(x)
}
else {
e.classList.remove(e.className)
}
}
}


div{
background-color: red;
}

.class0{
background-color: blue;
}

.class1{
background-color: purple;
}

Answer

As @Patrick suggested do this:

  window.onload = function(){
    var elements = document.getElementsByTagName("div")

    for(var i = 0; i < elements.length; i++){
      elements[i].addEventListener("click", a.bind(window, elements[i],i), false)
    }

    function a(e, x){
      if(!e.className){
        e.className = "class".concat(x)
      }
      else {
        e.classList.remove(e.className)
      }
    }
  }

You were invoking the function a and assigning its result as an event handler.

With bind you create a function that will invoke a passing as arguments the element and the index.

Comments