Tom
Tom

Reputation: 845

Javascript function inside loop

Any one have any idea why this doesn't work as expected? Just fires alerts on page load.

var div = document.querySelectorAll('.div'); // NodeList of all instances of '.div'

var eventFunction = function() {
  alert('ggdf');
};


for(var i = 0; i < div.length; i++) { // Begin '.div' NodeList loop

  div[i].addEventListener('click', eventFunction(), false); // Click function on all instances of '.div'

} // End '.div' NodeList loop

Upvotes: 0

Views: 57

Answers (2)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

Your executing the function when passing it to the eventListener function, instead use:

for(var i = 0; i < div.length; i++) {  
  div[i].addEventListener('click', eventFunction, false); //notice no ()
}

Functions can be passed as arguments the same way as other variables, but when you pass them with () after them your invoking the function and the object/value returned by the function is passed as the argument.

Also unless you have added a class div to all your divs I think you want to use a tag selector:

var div = document.querySelectorAll('div'); 

JS Fiddle: http://jsfiddle.net/rG3AC/1/

Upvotes: 5

Sterling Archer
Sterling Archer

Reputation: 22395

You need to bind the function so that it doesn't trigger immediately.

div[i].addEventListener('click', eventFunction.bind(), false);

Upvotes: 0

Related Questions