Skip to content
Advertisement

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.

Advertisement

Answer

You need to remove event listener from each clicked element:

function counter(){
    count++;
    this.removeEventListener('click', counter);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement