Function fired even element doesn't get clicked

Hi guys,

I’ve this simple html structure:

<a href="#"><img id=show src="images/magic.svg" /></a>

<div id=showme>
	I'm revealed.
</div>

The CSS:

#showme {
	display: none;
	padding: 0.6em;
}

And the JS:

var a = document.getElementById('show');

var b = (x) => {
	let y = document.getElementById(x);
	if (y != undefined)
		(y.style.display !== 'block') ? y.style.display = 'block' : y.style.display = 'none';
}

a.addEventListener('click', b('showme'), false);

Why the #showme div shows up instantly without any click? How to fix this?

Thank you,

because you immediately invoke the function. you do not even define a click handler (since you assign undefined as handler and not a function).

there are basically two ways to solve that, a) use a closure and b) save the target id in the clicked element.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.