Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 217
goggelz Avatar asked Feb 11 '23 11:02

goggelz


1 Answers

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.

like image 96
Jackson Avatar answered Feb 14 '23 00:02

Jackson