KingOfLeon KingOfLeon - 6 months ago 8
Javascript Question

Why is the "hidden" class applied to an element BEFORE it is clicked?

This is my JS code:

var btn = document.querySelector("button");
btn.addEventListener("click", hide(this, true));
function hide(event, reflow) {
if(reflow) {
document.querySelector(".great").classList.add("hidden");
}
}


Could anybody please shed some light as to why this is happening?

Answer

@blex is correct in explaining why the function executes immediately, but the signature you have seems like you are trying to use Function.prototype.call. Here's what I suggest using:

btn.addEventListener('click', function(event){ hide.call(this, event, true); });

What this does is pass the context of the anonymous function (the function(event){...}) to hide() and sets the first two arguments e and reflow to event and true.

See MDN MouseEvent for what sort of properties the event object contains.