[javascript] Prevent BODY from scrolling when a modal is opened

I want my body to stop scrolling when using the mousewheel while the Modal (from http://twitter.github.com/bootstrap) on my website is opened.

I've tried to call the piece of javascript below when the modal is opened but without success

$(window).scroll(function() { return false; });

AND

$(window).live('scroll', function() { return false; });

Please note our website dropped support for IE6, IE7+ needs to be compatible though.

This question is related to javascript jquery css scroll

The answer is


I had a sidebar that was generated by checkbox hack. But the main idea is to save the document scrollTop and not to change it during scrolling the window.

I just didn't like the page jumping when body becomes 'overflow: hidden'.

_x000D_
_x000D_
window.addEventListener('load', function() {_x000D_
    let prevScrollTop = 0;_x000D_
    let isSidebarVisible = false;_x000D_
_x000D_
    document.getElementById('f-overlay-chkbx').addEventListener('change', (event) => {_x000D_
        _x000D_
        prevScrollTop = window.pageYOffset || document.documentElement.scrollTop;_x000D_
        isSidebarVisible = event.target.checked;_x000D_
_x000D_
        window.addEventListener('scroll', (event) => {_x000D_
            if (isSidebarVisible) {_x000D_
                window.scrollTo(0, prevScrollTop);_x000D_
            }_x000D_
        });_x000D_
    })_x000D_
_x000D_
});
_x000D_
_x000D_
_x000D_


For Bootstrap, you might try this (working on Firefox, Chrome and Microsoft Edge) :

body.modal-open {
    overflow: hidden;
    position:fixed;
    width: 100%;
}

Hope this helps...


Try this one:

.modal-open {
    overflow: hidden;
    position:fixed;
    width: 100%;
    height: 100%;
}

it worked for me. (supports IE8)


You need to go beyond @charlietfl's answer and account for scrollbars, otherwise you may see a document reflow.

Opening the modal:

  1. Record the body width
  2. Set body overflow to hidden
  3. Explicitly set the body width to what it was in step 1.

    var $body = $(document.body);
    var oldWidth = $body.innerWidth();
    $body.css("overflow", "hidden");
    $body.width(oldWidth);
    

Closing the modal:

  1. Set body overflow to auto
  2. Set body width to auto

    var $body = $(document.body);
    $body.css("overflow", "auto");
    $body.width("auto");
    

Inspired by: http://jdsharp.us/jQuery/minute/calculate-scrollbar-width.php


I'm not 100% sure this will work with Bootstrap but worth a try - it worked with Remodal.js which can be found on github: http://vodkabears.github.io/remodal/ and it would make sense for the methods to be pretty similar.

To stop the page jumping to the top and also prevent the right shift of content add a class to the body when the modal is fired and set these CSS rules:

body.with-modal {
    position: static;
    height: auto;
    overflow-y: hidden;
}

It's the position:static and the height:auto that combine to stop the jumping of content to the right. The overflow-y:hidden; stops the page from being scrollable behind the modal.


This works

body.modal-open {
   overflow: hidden !important;
}

You could use the following logic, I tested it and it works(even in IE)

   <html>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">

var currentScroll=0;
function lockscroll(){
    $(window).scrollTop(currentScroll);
}


$(function(){

        $('#locker').click(function(){
            currentScroll=$(window).scrollTop();
            $(window).bind('scroll',lockscroll);

        })  


        $('#unlocker').click(function(){
            currentScroll=$(window).scrollTop();
            $(window).unbind('scroll');

        })
})

</script>

<div>

<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<button id="locker">lock</button>
<button id="unlocker">unlock</button>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

</div>

Warning: The option below is not relevant to Bootstrap v3.0.x, as scrolling in those versions has been explicitly confined to the modal itself. If you disable wheel events you may inadvertently prevent some users from viewing the content in modals that have heights greater than the viewport height.


Yet Another Option: Wheel Events

The scroll event is not cancelable. However it is possible to cancel the mousewheel and wheel events. The big caveat is that not all legacy browsers support them, Mozilla only recently adding support for the latter in Gecko 17.0. I don't know the full spread, but IE6+ and Chrome do support them.

Here's how to leverage them:

$('#myModal')
  .on('shown', function () {
    $('body').on('wheel.modal mousewheel.modal', function () {
      return false;
    });
  })
  .on('hidden', function () {
    $('body').off('wheel.modal mousewheel.modal');
  });

JSFiddle


For those wondering how to get the scroll event for the bootstrap 3 modal:

$(".modal").scroll(function() {
    console.log("scrolling!);
});

Many suggest "overflow: hidden" on the body, which will not work (not in my case at least), since it will make the website scroll to the top.

This is the solution that works for me (both on mobile phones and computers), using jQuery:

    $('.yourModalDiv').bind('mouseenter touchstart', function(e) {
        var current = $(window).scrollTop();
        $(window).scroll(function(event) {
            $(window).scrollTop(current);
        });
    });
    $('.yourModalDiv').bind('mouseleave touchend', function(e) {
        $(window).off('scroll');
    });

This will make the scrolling of the modal to work, and prevent the website from scrolling at the same time.


A small note for those in SharePoint 2013. The body already has overflow: hidden. What you are looking for is to set overflow: hidden on div element with id s4-workspace, e.g.

var body = document.getElementById('s4-workspace');
body.className = body.className+" modal-open";

Why not to do that as Bulma does? When modal is-active then add to html their class .is-clipped which is overflow: hidden!important; And thats it.

Edit: Okey, Bulma has this bug, so you must add also other things like

html.is-modal-active {
  overflow: hidden !important;
  position: fixed;
  width: 100%; 
}

My solution for Bootstrap 3:

.modal {
  overflow-y: hidden;
}
body.modal-open {
  margin-right: 0;
}

because for me the only overflow: hidden on the body.modal-open class did not prevent the page from shifting to the left due to the original margin-right: 15px.


Based on this fiddle: http://jsfiddle.net/dh834zgw/1/

the following snippet (using jquery) will disable the window scroll:

 var curScrollTop = $(window).scrollTop();
 $('html').toggleClass('noscroll').css('top', '-' + curScrollTop + 'px');

And in your css:

html.noscroll{
    position: fixed;
    width: 100%;
    top:0;
    left: 0;
    height: 100%;
    overflow-y: scroll !important;
    z-index: 10;
 }

Now when you remove the modal, don't forget to remove the noscroll class on the html tag:

$('html').toggleClass('noscroll');

I'm not sure about this code, but it's worth a shot.

In jQuery:

$(document).ready(function() {
    $(/* Put in your "onModalDisplay" here */)./* whatever */(function() {
        $("#Modal").css("overflow", "hidden");
    });
});

As I said before, I'm not 100% sure but try anyway.


You could try setting body size to window size with overflow: hidden when modal is open


I am using this vanilla js function to add "modal-open" class to the body. (Based on smhmic's answer)

function freezeScroll(show, new_width)
{
    var innerWidth = window.innerWidth,
        clientWidth = document.documentElement.clientWidth,
        new_margin = ((show) ? (new_width + innerWidth - clientWidth) : new_width) + "px";

    document.body.style.marginRight = new_margin;
    document.body.className = (show) ? "modal-open" : "";
};

Sadly none of the answers above fixed my issues.

In my situation, the web page originally has a scroll bar. Whenever I click the modal, the scroll bar won't disappear and the header will move to right a bit.

Then I tried to add .modal-open{overflow:auto;} (which most people recommended). It indeed fixed the issues: the scroll bar appears after I open the modal. However, another side effect comes out which is that "background below the header will move to the left a bit, together with another long bar behind the modal"

Long bar behind modal

Luckily, after I add {padding-right: 0 !important;}, everything is fixed perfectly. Both the header and body background didn't move and the modal still keeps the scrollbar.

Fixed image

Hope this can help those who are still stuck with this issue. Good luck!


I just done it this way ...

$('body').css('overflow', 'hidden');

But when the scroller dissapeared it moved everything right 20px, so i added

$('body').css('margin-right', '20px');

straight after it.

Works for me.


   $('.modal').on('shown.bs.modal', function (e) {
      $('body').css('overflow-y', 'hidden');
   });
   $('.modal').on('hidden.bs.modal', function (e) {
      $('body').css('overflow-y', '');
   });

Hiding the overflow and fixing the position does the trick however with my fluid design it would fix it past the browsers width, so a width:100% fixed that.

body.modal-open{overflow:hidden;position:fixed;width:100%}

Here's my vanilla JS solution based on @jpap jquery:

let bodyElement = document.getElementsByTagName('body')[0];

// lock body scroll
    let width = bodyElement.scrollWidth;
    bodyElement.classList.add('overflow-hidden');
    bodyElement.style.width = width + 'px';

// unlock body scroll
    bodyElement.classList.remove('overflow-hidden');
    bodyElement.style.width = 'auto';

Simply hide the body overflow and it makes body not scrolling. When you hide the modal, revert it to automatic.

Here is the code:

$('#adminModal').modal().on('shown', function(){
    $('body').css('overflow', 'hidden');
}).on('hidden', function(){
    $('body').css('overflow', 'auto');
})

worked for me

$('#myModal').on({'mousewheel': function(e) 
    {
    if (e.target.id == 'el') return;
    e.preventDefault();
    e.stopPropagation();
   }
});

Adding the class 'is-modal-open' or modifying style of body tag with javascript is okay and it will work as supposed to. But the problem we gonna face is when the body becomes overflow:hidden, it will jump to the top, ( scrollTop will become 0 ). This will become a usability issue later.

As a solution for this problem, instead of changing body tag overflow:hidden change it on html tag

$('#myModal').on('shown.bs.modal', function () {
  $('html').css('overflow','hidden');
}).on('hidden.bs.modal', function() {
  $('html').css('overflow','auto');
});

This issue is fixed, Solution: Just open your bootstap.css and change as below

body.modal-open,
.modal-open .navbar-fixed-top,
.modal-open .navbar-fixed-bottom {
  margin-right: 15px;
}

to

 body.modal-open,
.modal-open .navbar-fixed-top,
.modal-open .navbar-fixed-bottom {
  /*margin-right: 15px;*/
}

Please view the below youtube video only less than 3min your issue will fix... https://www.youtube.com/watch?v=kX7wPNMob_E


I found a working solution after doing some 8-10 hours research on StackOverflow itself.

The breakthrough

$('.modal').is(':visible');

So I have built a function to check if any modal is open which will periodically add class *modal-open** to the

 setInterval(function()
     {
         if($('.modal').is(':visible')===true)
         {
             $("body").addClass("modal-open");
         }
         else
         {
             $("body").removeClass("modal-open");
         }

     },200);

The reason to use $(".modal") here is because all modals (in Bootstrap) use class modal (fade/show is as per the state)

So my modals are now running perfectly without the body getting scrolled.

This is a bug/unheard issue in GitHub as well but nobody's bothered.


None of the above answers worked perfectly for me. So I found another way which works well.

Just add a scroll.(namespace) listener and set scrollTop of the document to the latest of it's value...

and also remove the listener in your close script.

// in case of bootstrap modal example:
$('#myModal').on('shown.bs.modal', function () {
  
  var documentScrollTop = $(document).scrollTop();
  $(document).on('scroll.noScroll', function() {
     $(document).scrollTop(documentScrollTop);
     return false;
  });

}).on('hidden.bs.modal', function() {

  $(document).off('scroll.noScroll');

});

update

seems, this does not work well on chrome. any suggestion to fix it ?


The best solution is the css-only body{overflow:hidden} solution used by most of these answers. Some answers provide a fix that also prevent the "jump" caused by the disappearing scrollbar; however, none were too elegant. So, I wrote these two functions, and they seem to work pretty well.

var $body = $(window.document.body);

function bodyFreezeScroll() {
    var bodyWidth = $body.innerWidth();
    $body.css('overflow', 'hidden');
    $body.css('marginRight', ($body.css('marginRight') ? '+=' : '') + ($body.innerWidth() - bodyWidth))
}

function bodyUnfreezeScroll() {
    var bodyWidth = $body.innerWidth();
    $body.css('marginRight', '-=' + (bodyWidth - $body.innerWidth()))
    $body.css('overflow', 'auto');
}

Check out this jsFiddle to see it in use.


/* =============================
 * Disable / Enable Page Scroll
 * when Bootstrap Modals are
 * shown / hidden
 * ============================= */

function preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
      e.preventDefault();
  e.returnValue = false;  
}

function theMouseWheel(e) {
  preventDefault(e);
}

function disable_scroll() {
  if (window.addEventListener) {
      window.addEventListener('DOMMouseScroll', theMouseWheel, false);
  }
  window.onmousewheel = document.onmousewheel = theMouseWheel;
}

function enable_scroll() {
    if (window.removeEventListener) {
        window.removeEventListener('DOMMouseScroll', theMouseWheel, false);
    }
    window.onmousewheel = document.onmousewheel = null;  
}

$(function () {
  // disable page scrolling when modal is shown
  $(".modal").on('show', function () { disable_scroll(); });
  // enable page scrolling when modal is hidden
  $(".modal").on('hide', function () { enable_scroll(); });
});

The above occurs when you use a modal inside another modal. When I open a modal inside another modal, the closing of the latter removes the class modal-open from the body. The fix of the issue depends on how you close the latter modal.

If you close the modal with html like,

<button type="button" class="btn" data-dismiss="modal">Close</button>

Then you have to add a listener like this,

$(modalSelector).on("hidden.bs.modal", function (event) {
    event.stopPropagation();
    $("body").addClass("modal-open");
    return false;
});

If you close the modal using javascript like,

$(modalSelector).modal("hide");

Then you have to run the command some time after like this,

setInterval(function(){$("body").addClass("modal-open");}, 300);

The accepted answer doesn't work on mobile (iOS 7 w/ Safari 7, at least) and I don't want MOAR JavaScript running on my site when CSS will do.

This CSS will prevent the background page from scrolling under the modal:

body.modal-open {
    overflow: hidden;
    position: fixed;
}

However, it also has a slight side-affect of essentially scrolling to the top. position:absolute resolves this but, re-introduces the ability to scroll on mobile.

If you know your viewport (my plugin for adding viewport to the <body>) you can just add a css toggle for the position.

body.modal-open {
    // block scroll for mobile;
    // causes underlying page to jump to top;
    // prevents scrolling on all screens
    overflow: hidden;
    position: fixed;
}
body.viewport-lg {
    // block scroll for desktop;
    // will not jump to top;
    // will not prevent scroll on mobile
    position: absolute; 
}

I also add this to prevent the underlying page from jumping left/right when showing/hiding modals.

body {
    // STOP MOVING AROUND!
    overflow-x: hidden;
    overflow-y: scroll !important;
}

this answer is a x-post.


Since for me this problem presented mainly on iOS, I provide the code to fix that only on iOS:

  if(!!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)) {
    var $modalRep    = $('#modal-id'),
        startScrollY = null, 
        moveDiv;  

    $modalRep.on('touchmove', function(ev) {
      ev.preventDefault();
      moveDiv = startScrollY - ev.touches[0].clientY;
      startScrollY = ev.touches[0].clientY;
      var el = $(ev.target).parents('#div-that-scrolls');
      // #div-that-scrolls is a child of #modal-id
      el.scrollTop(el.scrollTop() + moveDiv);
    });

    $modalRep.on('touchstart', function(ev) {
      startScrollY = ev.touches[0].clientY;
    });
  }

You should add overflow: hidden in HTML for a better cross-platform performance.

I would use

html.no-scroll {
    overflow: hidden;
}

As of November 2017 Chrome Introduced a new css property

overscroll-behavior: contain;

which solves this problem although as of writing has limited cross browser support.

see below links for full details and browser support


This worked for me:

$("#mymodal").mouseenter(function(){
   $("body").css("overflow", "hidden"); 
}).mouseleave(function(){
   $("body").css("overflow", "visible");
});

HTML:

<body onscroll="stop_scroll()">

javascript:

function stop_scroll(){
    scroll(0,0) ;
}

If you set a flag (bool) inside stop_scroll(), you can decide when to engage it (if you want it only temporarely).

This will reset scrolling every time some element overflows the body boundaries and the windows tends to scroll (this is totally independent of scrollbars; overflow : hidden has nothing to do with it).


This is the best solution for me:

Css:

.modal {
     overflow-y: auto !important;
}

And Js:

modalShown = function () {
    $('body').css('overflow', 'hidden');
},

modalHidden = function () {
    $('body').css('overflow', 'auto');
}

Couldn't make it work on Chrome just by changing CSS, because I didn't want the page to scroll back to the top. This worked fine:

$("#myModal").on("show.bs.modal", function () {
  var top = $("body").scrollTop(); $("body").css('position','fixed').css('overflow','hidden').css('top',-top).css('width','100%').css('height',top+5000);
}).on("hide.bs.modal", function () {
  var top = $("body").position().top; $("body").css('position','relative').css('overflow','auto').css('top',0).scrollTop(-top);
});

Most of the pieces are here, but I don't see any answer that puts it all together.

The problem is threefold.

(1) prevent the scroll of the underlying page

$('body').css('overflow', 'hidden')

(2) and remove the scroll bar

var handler = function (e) { e.preventDefault() }
$('.modal').bind('mousewheel touchmove', handler)

(3) clean up when the modal is dismissed

$('.modal').unbind('mousewheel touchmove', handler)
$('body').css('overflow', '')

If the modal is not full-screen then apply the .modal bindings to a full screen overlay.


Try this code:

$('.entry_details').dialog({
    width:800,
    height:500,
    draggable: true,
    title: entry.short_description,
    closeText: "Zamknij",
    open: function(){
        //    blokowanie scrolla dla body
        var body_scroll = $(window).scrollTop();
        $(window).on('scroll', function(){
            $(document).scrollTop(body_scroll);
        });
    },
    close: function(){
        $(window).off('scroll');
    }
}); 

If modal are 100% height/width "mouseenter/leave" will work to easily enable/disable scrolling. This really worked out for me:

var currentScroll=0;
function lockscroll(){
    $(window).scrollTop(currentScroll);
} 
$("#myModal").mouseenter(function(){
    currentScroll=$(window).scrollTop();
    $(window).bind('scroll',lockscroll); 
}).mouseleave(function(){
    currentScroll=$(window).scrollTop();
    $(window).unbind('scroll',lockscroll); 
});

React , if you are looking for

useEffect in the modal that is getting popedup

 useEffect(() => {
    document.body.style.overflowY = 'hidden';
    return () =>{
      document.body.style.overflowY = 'auto';
    }
  }, [])

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to scroll

How to window.scrollTo() with a smooth effect Angular 2 Scroll to bottom (Chat style) Scroll to the top of the page after render in react.js Get div's offsetTop positions in React RecyclerView - How to smooth scroll to top of item on a certain position? Detecting scroll direction How to disable RecyclerView scrolling? How can I scroll a div to be visible in ReactJS? Make a nav bar stick Disable Scrolling on Body