How to disable scrolling in the background when opening a mobile menu?

I am creating a mobile responsive website with a navigation menu. When I get to the bottom of the menu - if I continue to scroll, when I get to the bottom of the menu, it scrolls the page in the background. How can i turn it off?

This is my jQuery code:

// When the document is loaded... $(document).ready(function() { $('#mob-menu-btn').click(function(){ $('.sports').slideToggle("slow"); }) $('#sub-menu').click(function(){ $('.sports2').slideToggle("slow"); }) }); 

and this is my CSS:

  .list{ width: 100%; overflow: hidden; overflow-y: auto; top: -10%; overflow: hidden; overflow-y: auto; } .sports li{ list-style-image:none; list-style-type: none; border-bottom: 2px solid #eeeeee; margin-bottom: 0px; margin-left: 0px; padding-top: 15px; padding-bottom: 15px; padding-left: 10px; width:100%; font-family: arial; text-decoration: none; overflow: hidden; } 
+8
source share
3 answers

When the menu is open, set the position fixed on the case. When you close it, delete this property. It is better to use the add / remove class.

  if($('#mob-menu').is(':visible')) { $('body').addClass("fixedPosition"); } else { $('body').removeClass("fixedPosition"); } 

  .fixedPosition { position: fixed; } 
+11
source

Instead of using position: fixed (which triggers a jump back when you open your menu), you can use overflow: hidden . If you are somewhere on your page and open the menu, it does not return to the top. (maybe jumping is the problem of how I wrote my code, but it was useful to me).

+9
source

There is also a slightly different approach to this problem. You can add the onclick event to your button. Then add / remove the class to your body (similar to the previous answer, but take it before considering). This is what works for me, but with a button button, I have a checkbox that checks, toggles my mobile menu.

Add this to your section:

 <script> function lockScroll() { if ($('body').hasClass('lock-scroll')) { $('body').removeClass('lock-scroll'); } else { $('body').addClass('lock-scroll'); } } </script> 

Then specify the class in the CSS file / section:

 .lock-scroll { overflow: hidden; } 

And this will be your button:

 <button type="button" id="#mob-menu-btn" onclick="lockScroll();">Click me!</button> 
+3
source

Source: https://habr.com/ru/post/1208054/


All Articles