L.Frederiksen L.Frederiksen - 3 years ago 126
Javascript Question

addEventListener execute code after "if" but doesn't execute code after "else" (onclick display)

Can anybody explain to me why when a code works normally, but the second I use addEventListener it won't read the "display none" function after

} else


I know there is a lot of codes and questions out there, where people ask about the onclick function. But I haven't found any on why I have to rewrite the code just because I use addEventListener.

So here it will open the menu but it won't close it again but if I remove the addEventListener it will.

document.getElementById("menu-item-11109").addEventListener("click", myFunction);

function myFunction() {
var x = document.getElementById('closemenu');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}


HTML

<li onclick="myFunction()" id="menu-item-11109">
<a>Opskrifter</a>
<ul id="closemenu">
<li>
<a href="https://kvalitet-extensions.dk/category/mad/">Mad og drikke</a>
</li>
</ul>

Answer Source
<li onclick="myFunction()" id="menu-item-11109">

You should pass a reference to your function that should happen onclick. but instead you are calling myfunction directly.

Solution:

<li onclick="myFunction" id="menu-item-11109">

Here I am passing a reference to myFunction to the onclick event.

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