AddEventListener click is executed before click

I want to pass parameters to click functions.

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 "goAlbum" function gets excecuted when it is created and then the function will no longer be canceled. what am I doing wrong?

+3


source to share


1 answer


goAlbum

was executed because you called the function. You didn't "create" the function. What you intend to do is provide addEventListener

logic to execute when something is clicked; this logic "calls goAlbum

". To do this, end the function call with 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);
});

      



Also, since it is impractical to create functions in a loopfor

, I refactored your code for use forEach

. I need to convert the NodeList

returned document.getElementsByClassName

to in Array

order to use forEach

hence the function toArray

.

+5


source







All Articles