skip to Main Content

I really hope you can help me with a problem I have. This is my first time asking anything so excuse me if I miss something but the problem is as follow:

I created a dropdown menu in WordPress with Elementor Pro with the following code, and I just cant seem to find a solution on how to prevent page scroll when the dropdown is active on mobile devices.

<script>
//Toggle mobile menu & change icon on click

 jQuery(function() {
 jQuery('.nav-icon').click(function(){
      jQuery('#nav-container').slideToggle(280);
           jQuery('.nav-icon i').toggleClass('change-icon');

  });   
        
// Close mobile menu on screen size

jQuery(window).on('resize', function(){
   let win = jQuery(this);
    if(win.width() > 1024){
      jQuery('#nav-container').show();
   } else {
     jQuery('#nav-container').hide();
   }
    
 });
});
</script>

I literally tried everything possible I found on the internet but with no luck. I am 99% sure I am making a mistake somewhere because coding is not my strength (not at all), so please any help will be highly appreciated!

2

Answers


  1. Chosen as BEST ANSWER

    Can someone help with the integration of the following code in my original one -

        function preventBehavior(e) {
        e.preventDefault(); 
    };
    
        document.addEventListener("touchmove", preventBehavior, {passive: false});
    

    How to enable it only on icon click and disable it on click as well?


  2. In order to prevent page scrolling when the dropdown menu is active on mobile devices, you can add a CSS class to the body element when the dropdown is toggled. This class will disable the scrolling behavior using CSS

    <script>
      jQuery(function($) {
        // Toggle mobile menu & change icon on click
        $('.nav-icon').click(function() {
          $('#nav-container').slideToggle(280);
          $('.nav-icon i').toggleClass('change-icon');
          
          // Add/remove class to body to disable/enable scrolling
          $('body').toggleClass('menu-open');
        });
    
        // Close mobile menu on screen resize
        $(window).on('resize', function() {
          let win = $(this);
          if (win.width() > 1024) {
            $('#nav-container').show();
            $('body').removeClass('menu-open'); // Remove the class to enable scrolling
          } else {
            $('#nav-container').hide();
          }
        });
      });
    </script>
    

    Now, you can add the following CSS to your theme or custom CSS to disable scrolling when the dropdown menu is active:

    body.menu-open {
      overflow: hidden;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search