0

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
0

2 Answers 2

5

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Ahh right I see, thanks for this, just getting to grips with library-less JS, coming from a PHP background little things keep tripping me up, thanks again!
0

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

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

1 Comment

Does not point out the acutal mistake - cant see how this one helps at all here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.