'Clicked drop down menu

When I click menu text that should toggle the menuContent the first time, it works as it shows the menuContent which is what is meant to be shown. However, after it shows it does not hide so the display = block does not go back to display = none.

I tried using a show value but it did not work so I used display = block instead in an if statement.

(By the way: menu = button that toggles text and menuContent = text that should be shown or hidden)

This is the JavaScript:

menu.addEventListener('click', menuClick, false);
menuContent.style.display = 'none'

function menuClick() {
    menuContent.classList.toggle('show');
    if (menuContent.style.display = 'none') {
        menuContent.style.display = 'block'
    } else {
        menuContent.style.display = 'none'
    }
}

So the first part of the if statement worked but not the else part.

How do I fix this?



Solution 1:[1]

menuContent.style.display = 'none'

should be

menuContent.style.display === 'none'

otherwise you're setting menuContent back to "display: none" again.

Remind '=' and '==='!

Solution 2:[2]

menuContent.style.display = 'none' is variable assignment, not a test for equality. You need to use === or == (loose check).

So, you always end up in the first situation because you always assign it to a value.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 liuyiqi1999
Solution 2 Dan