Search code examples
javascriptdom-events

For loop with events


I'm working with along with an online tutorial and trying to understand the code below. What I don't get is why this works more than two times. When the loop has been executed two times i == len and the condition i < len isn't true anymore. So how come it's possible to toggle the different classes more than two times?

My guess is that when the condition is false i gets set to 0 again, did I understand that correctly? Hope someone can help me, I didn't find an explanation of this particular problem anywhere online.

HTML

 <button>Normal</button>
 <button>Changed</button>

CSS

.normal {background-color: white;color:black;}
.changed {background-color: black;color:white;}

JavaScript

(function() {
var buttons = document.getElementsByTagName("button");

for (var i = 0, len = buttons.length; i < len; i +=1)
  buttons[i].onclick = function() {
    var className = this.innerHTML.toLowerCase();
    document.body.className = className;
 }}
}());

Solution

  • The for loop gets excecuted only once and iterates through all buttons. In the for loops body, you define an onclick function for each button.

    So, before you can click anywhere the loop already has finished, and added an onclick function to each single button, which will be called everytime, you click on that button.

    With button[i].onclick = function() {...} you add an event handler function to the buttons click event.

    You should read more about event handlers in general.