JQuery / CSS: fixed overlay shouldn't allow background scroll?

I have an overlay block that is fixed and centered on the screen. The page itself is quite long and has a vertical scrollbar.

I would like to disable scrolling of the page itself when the overlay is displayed. However, I cannot completely disable scrolling, because some overlays have overflow-y:scroll for themselves. Thus, the content of the overlay should scroll, but the page itself should be stuck.

Any idea how to solve this using jquery or css?

+8
javascript jquery html css scroll
source share
5 answers

The fastest and dirtiest way I can come up with is to attach an event listener to the window for scroll events and prevent Default () if the overlay is visible.

like that (using jquery).

  window.addEventListener('scroll', function(e){ var el = $('.overlay.active'); if( el.length > 0 ){ e.preventDefault(); } }); 

Hope this is what you are looking for.

+7
source share

You can set body to overflow: hidden . This will prevent scrolling. Declarations of overcrowding remain unchanged. I did a little fiddle .

+3
source share

Just customization for Marc jQuery solution. My code disables body scrolling when an overlay appears, then when the close or overlay button is pressed, body scrolling is activated again.

 /*We disable the scroll*/ $(function() { /*This is where we specify what button is being clicked to open the overlay, change at will.*/ $('#overlay1').click(function() { /*This is where we specify what part of the page is gonna disable the scroll, in this case the body.*/ $('body') .css('overflow', 'hidden'); }); /*Now we re-enable the scroll*/ /*This is where we specify the the part of the overlay that is being clicked to close it, in this case, the body and the .close, change at will.*/ $('body, .close').click(function() { /*This is where we specify the part of the page we are re-enabling the scroll, in this case the body.*/ $('body') .css('overflow', 'visible'); }); }); 

Here's a little JSFiddle of my action script.

+1
source share

You can position the overlay as {position: fixed;} . This will keep your overlay on your screen , even if your page scrolls.

0
source share

You can create a container with full width and full height, position: fixed . And inside this container, create your actual information overlay. The container basically hides the user from scrolling or interacting with the page.

0
source share

All Articles