javascript - addEventListener click executed before clicked -


i want pass on parameters in click function.

var albums = document.getelementsbyclassname("album"); for(var = 0; i<albums.length; i++){     document.getelementbyid(albums[i].id).addeventlistener("click", goalbum(albums[i].id), false); } 

however, function "goalbum" gets excecuted when created, , function won't excecute anymore. doing wrong?

goalbum getting executed because called function. weren't "creating" function. intended supply addeventlistener logic execute when clicked; logic being "invoke goalbum". this, wrap function call in anonymous function.

function toarray(list) {     return array.prototype.slice.call(list); }  var albums = toarray(document.getelementsbyclassname("album")); albums.foreach(function (album) {     document.getelementbyid(album.id).addeventlistener("click", function () {         goalbum(album.id);     }, false); }); 

additionally, because it unwise create functions in for loop, have refactored code use foreach. need convert nodelist returned document.getelementsbyclassname array in order use foreach, hence toarray function.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -