Afn
Afn

Reputation: 1

addEventListener "click" only runs once with if statement

I have an addEventListener for a dropdown menu and when I click it for the first time the menu appears, and if I click again it disappears correctly. However, after that if I try again nothing happens. If I get rid of the if statements and use a simple alert inside the function it works every time, but this if statement seems to be troublesome.

document.getElementById("menu").addEventListener("click",navigation);
function navigation() {
var navMenu = document.getElementById("navigation");
var list = document.getElementById("list");
if (navMenu.style.height == 0) {
    navMenu.style.height = "190px";
    list.style.display = "flex";
}
else {
    navMenu.style.height = "0";
    list.style.display = "none";
}
}

Upvotes: 0

Views: 264

Answers (3)

Fotis Adamakis
Fotis Adamakis

Reputation: 284

The element height is reported in pixels so updating the code like this should work.

if (navMenu.style.height === '0px') {

Here is a codepen http://codepen.io/anon/pen/ZOXAzd

Upvotes: 2

Mako
Mako

Reputation: 168

In the condition, change

if (navMenu.style.height == 0)

to

if (navMenu.style.height == '0px')

and it should work.

Upvotes: 1

r3fresh_
r3fresh_

Reputation: 87

I am not sure about this but have you tried to do = 0 instead of = '0'?

I hope this helped, good luck.

Upvotes: 0

Related Questions