Home > Software engineering >  Clicked drop down menu
Clicked drop down menu

Time:04-24

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?

CodePudding user response:

menuContent.style.display = 'none'

should be

menuContent.style.display === 'none'

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

Remind '=' and '==='!

CodePudding user response:

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.

  • Related