Skip to content

Disable an on click event after the first click

I have a function that counts every time a user clicks on and image on the page:

for(var i = 0; i < document.getElementsByClassName("face").length; i++){
    document.getElementsByClassName("face")[i].addEventListener("click", counter)
}

function counter(){
    count ++;
}

And I want to disable it after the first click so it won’t keep counting duplicate clicks of the same picture. I know adding this.onclick=null on the HTML tag will work, but I’m wondering if there a way to do this on the javascript file itself so I don’t need to put javascript onto my HTML file.

Answer

You need to remove event listener from each clicked element:

function counter(){
    count++;
    this.removeEventListener('click', counter);
}