skip to Main Content

I’m working on a one-page WordPress website and the page scrolls to each section when a menu item is clicked. It works well on desktops/laptops but on mobile devices when the hamburger menu is tapped, the menu opens and it blocks the screen. I would like to hide the dropdown menu list/section only on mobile. At the moment I have to close the menu by tapping on "X" close button.

I have searched for a solution and I found some JS code here in Stackoverflow but it has not worked.

Here is the JS code:

<script>
  function closeFunction()
  { 
     document.getElementById('bs-example-navbar-collapse-1').style.display='none';
  }
</script>

I’m not so experienced in JS but with some guidance I fix this, please help.

Screens:
enter image description here

2

Answers


  1. If you want to hide menu then you just need to hide hamburger icon (because it will not have functionality at all), right? If there is no hamburger to click, dropdown menu will not appear. You just need to use CSS: define min width when the hamburger is visible. You should consider mobile view can be landscape and portrait (widths are different). It is possible to handle screen orientation too, but then you need Javascript.

    Also, there is a way to detect if device is mobile device, but I would not recommend doing that. Detecting a mobile browser

    Edited

    You should define onclick event that triggers your function

    <script> 
    document.getElementById("id-of-element-event-is-attached-to").onclick = closeFunction; 
    function closeFunction() { 
      document.getElementById('bs-example-navbar-collapse-1').style.display='none'; 
    } 
    </script>
    
    Login or Signup to reply.
  2. You can simply make an event listener, and hide it.

    <script>
      document.addEventListener('DOMContentLoaded', function() {
        // Function to close the menu
        function closeMenu() {
          var menu = document.getElementById('bs-example-navbar-collapse-1');
          menu.style.display = 'none'; // Hide the menu
        }
    
        // Get all the menu links
        var menuLinks = document.querySelectorAll('#bs-example-navbar-collapse-1 a');
    
        // Add click event listeners to all menu links
        menuLinks.forEach(function(link) {
          link.addEventListener('click', closeMenu);
        });
      });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search