KingOfLeon KingOfLeon - 2 years ago 58
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) {

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

Answer Source

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

btn.addEventListener('click', function(event){, 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download