skip to Main Content

I’m currently improving my website for the use with mobile devices. Therefore I’m trying to open a menu with a click onto a equiv button. The menu is a fixed div with scrollable content and should appear and disappear with a click onto the button. Either option is working if set through the display property in CSS, but I’m not able to toggle the visibility through JavaScript.

function ToggleDiv() {
  var v = document.getElementById('equiv-submenu');

  if (v.style.display == '' || v.style.display == 'none') {
    v.style.display = 'block';
  }
  else {
    v.style.display = 'none';
  }
}
<div id="equiv" onclick="ToggleDiv()">
  <p>&equiv;</p>
</div>

<div id="equiv-submenu">
  <div id="equiv-submenu-content">
    ...
  </div>
</div>

3

Answers


  1. function ToggleDiv() {
        var v = document.getElementById('equiv-submenu');
        
        if (v.style.display === 'none' || v.style.display === '') {
            v.style.display = 'block';
        } else {
            v.style.display = 'none';
        }
    }
    
    // Add event listener to the button
    document.getElementById('equiv').addEventListener('click', ToggleDiv);
    
    <div id="equiv">
        <p>&equiv;</p>
    </div>
    
    <div id="equiv-submenu" style="display: none;">
        <!-- Your menu content here -->
    </div>
    

    Ensure that your equiv-submenu div has an initial display: none style, either inline or in your CSS

    Login or Signup to reply.
  2. Check the computed style to handle the case where display is set in CSS

    function ToggleDiv() {
        var v = document.getElementById('equiv-submenu');
    
        if (window.getComputedStyle(v).display === 'none') {
            v.style.display = 'block';
        } else {
            v.style.display = 'none';
        }
    }
    
    Login or Signup to reply.
  3. You can solve your problem by replacing the code below with your javascript code:

    document.getElementById('equiv').addEventListener('click', () => {
        var v = document.getElementById('equiv-submenu');
        v.style.display = (v.style.display === 'none' || v.style.display === '') ? 'block' : 'none';
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search