TheLemonSong
TheLemonSong

Reputation: 21

Javascript Conditional Statement Fails

I'm trying to toggle the display on an element, and whilst I have used the conditional statement using below of '===' on say an ID of an element, which worked, I cannot get this code to work.

Does anyone know why the condition 'if (smallnavbar[0].style.display === 'none')' doesn't work? Is there a way to make the code work (toggle the display between none and flex)?

Thanks in advance!

function displayMenu(){
  var smallnavbar = document.getElementsByClassName("small-navbar-tabs");
  if (smallnavbar[0].style.display === 'none') {
    smallnavbar[0].style.display = 'flex';
  }
  else if (smallnavbar[0].style.display === 'flex') {
    smallnavbar[0].style.display = 'none';
  }
}

Upvotes: 0

Views: 51

Answers (1)

ZER0
ZER0

Reputation: 25332

style.display is referring to the inline style (<div style='display:block'></div>). If the display is set by a class in a stylesheet, the display value will be an empty string.

In such case, neither conditions will be true, and therefore it will seems to you that are "failing".

You can simply double check my hypothesis with a console.log before the if statement (of course assuming the displayMenu is called).

There are several workaround for fixing this. You can:

  1. Check the computed style of the element instead of the inline one:

    function displayMenu(){
      var smallnavbar = document.getElementsByClassName("small-navbar-tabs");
      var display = window.getComputedStyle(smallnavbar[0], "").display;
    
      smallnavbar[0].style.display = display === 'none' ? 'flex' : 'none';
    }
    

    }

  2. Having a separate class name for "flex" and "none" and check that instead of the value (if the browser support or you provide a shim for classList that would be easy:

    smallnavbar[0].classList.toggle("flexible"); 
    
  3. Assuming the default value – e.g. you know that all small-navbar-tabs by default have display:none for example, therefore you could have:

    if (smallnavbar[0].style.display === "flex") {
      smallnavbar[0].style.display = ""; // remove the inline style
    } else {
      // since we're adding the inline style here,
      // it would pass the first check in the future.
      smallnavbar[0].style.display = "flex";
    }
    

Upvotes: 2

Related Questions