addEventListener click executed before clicked
I want to pass over parameters in the click function.
var albums = document.getElementsByClassName("album");
for(var i = 0; i<albums.length; i++){
document.getElementById(albums[i].id).addEventListener("click", goAlbum(albums[i].id), false);
}
However, the function goAlbum
gets executed when it is created, and then the function won't execute anymore.
What am I doing wrong?
goAlbum
was getting executed because you called the function. You weren't "creating" a function. What you intended to do was supply addEventListener
with logic to execute when something is clicked; that logic being "invoke goAlbum
". To do this, wrap the function call in an 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 is unwise to create functions in a for
loop, I have refactored your code to use forEach
. I need to convert the NodeList
returned by document.getElementsByClassName
to an Array
in order to use forEach
, hence the toArray
function.