Ask coding questions

← Back to all posts
How to pass a non-event argument addEventListender
sodalover (14)
var timesClicked = 0;

element.addEventListener('clicked', function(timesClicked){
    alert(timesClicked);
})

I think my code is pretty self-explanatory. Every time I click, I want the page to create an alert of how many times I've clicked somewhere on the element. However, the code instead alerts me to a [mouseObject]. Is there a way to pass anything other than event arguments when using addEventListener?

Answered by ruiwenge2 (1186) [earned 5 cycles]
View Answer
Comments
hotnewtop
ruiwenge2 (1186)

dont provide the timesClicked argument in the function

like this:

var timesClicked = 0;
var element = document.querySelector("button");
element.addEventListener('click', function(){
    alert(timesClicked);
});