skip to Main Content

I want to change the display property of a div tag based on its current display property.

When display = "None", it should switch to "flex" by clicking on it and viseversa.

I wrote the following js code:

window.onload = function showHideSideMenuMyFolders() {

    var test = document.getElementById("sideMenuLowerPartFolders_MyFolders");
    
    if (test.style.display === "Flex") {
        test.style.display = "None";
    }
    else {
        test.style.display = "Flex";
    }
}

It should activate by clicking on a span element in the DOM.

<span id="showSideMenuMyFolders" onclick="showHideSideMenuMyFolders()">

However, it is not working.

Can somebody see my mistake?

3

Answers


  1. Although setting style.display can be done in a case insensitive way (like "Flex" or "flex" or "FLEX"), when reading that style property, it will be in all lowercase, so "flex". This means your if condition will never be true. You have to compare with the lowercase "flex".

    Login or Signup to reply.
  2. The function you are creating is only getting executed once on load.
    If you want to use it when the page has ended loading, and on click, declare it before and use it like you’ve done. If you dont need the code to be executed once on load, just dont use the `window.onload’ line.
    Also, display properties are in lowercase.

    const showHideSideMenuMyFolders = () => {
          var test = document.getElementById("sideMenuLowerPartFolders_MyFolders");
    
          if (test.style.display === "flex") {
              test.style.display = "none";
          }
          else {
              test.style.display = "flex";
          }
    }
    
    window.onload = showHideSideMenuMyFolders();
    
    Login or Signup to reply.
  3. You’re attaching the function to the "window.onload" try just to create a normal function without attach it to "window.onload"

    To avoid the use of "window.onload", you can insert the JS on footer, which is recommended.

    <aside id="sideMenuLowerPartFolders_MyFolders" style="display:none;">Side Menu</aside>
    <span id="showSideMenuMyFolders" onclick="showHideSideMenuMyFolders()" style="cursor:pointer">open menu</span>
    <script>
      function showHideSideMenuMyFolders() {
        let test = document.getElementById("sideMenuLowerPartFolders_MyFolders");
    
        if (test.style.display === "flex") {
          test.style.display = "none";
        } else {
          test.style.display = "flex";
        }
      };
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search