548

I'm using the scrollTo jQuery plugin and would like to know if it is somehow possible to temporarily disable scrolling on the window element through Javascript? The reason I'd like to disable scrolling is that when you scroll while scrollTo is animating, it gets really ugly ;)

Of course, I could do a $("body").css("overflow", "hidden"); and then put it back to auto when the animation stops, but it would be better if the scrollbar was still visible but inactive.

2
  • 14
    If it is still showing, then the user is trained to think that it must be functioning. If the dose not move or dose not respond, then it will break the users mental model of how you page works and result in confusion. I would just find a better way of dealing with scrolling whilst animating, like for instance stopping the animation. Commented Jan 22, 2011 at 19:31
  • Another solution: stackoverflow.com/questions/9280258/…
    – gdbj
    Commented Aug 31, 2017 at 20:13

50 Answers 50

908

The scroll event cannot be canceled. But you can do it by canceling these interaction events:
Mouse & Touch scroll and Buttons associated with scrolling.

[Working demo]

// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = {37: 1, 38: 1, 39: 1, 40: 1};

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

function preventDefaultForScrollKeys(e) {
  if (keys[e.keyCode]) {
    preventDefault(e);
    return false;
  }
}

// modern Chrome requires { passive: false } when adding event
var supportsPassive = false;
try {
  window.addEventListener("test", null, Object.defineProperty({}, 'passive', {
    get: function () { supportsPassive = true; } 
  }));
} catch(e) {}

var wheelOpt = supportsPassive ? { passive: false } : false;
var wheelEvent = 'onwheel' in document.createElement('div') ? 'wheel' : 'mousewheel';

// call this to Disable
function disableScroll() {
  window.addEventListener('DOMMouseScroll', preventDefault, false); // older FF
  window.addEventListener(wheelEvent, preventDefault, wheelOpt); // modern desktop
  window.addEventListener('touchmove', preventDefault, wheelOpt); // mobile
  window.addEventListener('keydown', preventDefaultForScrollKeys, false);
}

// call this to Enable
function enableScroll() {
  window.removeEventListener('DOMMouseScroll', preventDefault, false);
  window.removeEventListener(wheelEvent, preventDefault, wheelOpt); 
  window.removeEventListener('touchmove', preventDefault, wheelOpt);
  window.removeEventListener('keydown', preventDefaultForScrollKeys, false);
}

UPDATE: fixed Chrome desktop and modern mobile browsers with passive listeners

39
  • 146
    Tip for other devs stuck in this trap: Do make sure you remove any and all 'e.stopPropagation()' calls from other jQuery attempts to stop scrolling, because not only does it not work, it prevents the event from bubbling to THIS code that DOES work. Hopefully my wasted 30 mins will help save someone else time :) Commented Jan 7, 2013 at 13:01
  • 4
    You can add 32 (space) to the disabled keys array (show in the code comments).
    – gblazex
    Commented Jun 30, 2013 at 13:28
  • 24
    I can scroll this like I always do: using middle button press and moving the mouse... Therefore this trick will not affect such users as me ;)
    – Denis V
    Commented Dec 22, 2013 at 11:34
  • 16
    The scrollbar is not disabled.
    – verism
    Commented Nov 12, 2014 at 12:22
  • 5
    I can still make it scroll by dragging a file over the top/bottom of the page. This also works by selecting text on the page and doing the same dragover the top/bottom. Commented Apr 19, 2016 at 18:58
506

Do it simply by adding a class to the body:

.stop-scrolling {
  height: 100%;
  overflow: hidden;
}

Add the class then remove when you want to re-enable scrolling, tested in IE, FF, Safari and Chrome.

$('body').addClass('stop-scrolling')
22
  • 4
    Got it! You have to handle the touchmove event, as with $('body').bind('touchmove', function(e){e.preventDefault()}). Edited this answer to include this mobile solution. Commented Nov 19, 2012 at 21:46
  • 3
    Cool, just have to make sure any inner scrolling can work in the modal for the touch device. Could do an overlay just underneath the modal and prevent the default touchmove on the overlay instead of body.
    – hallodom
    Commented Nov 20, 2012 at 9:43
  • 86
    While this solution does work, it has the (potentially) undesirable effect of scrolling back to the top of the page.
    – Matt
    Commented Feb 28, 2013 at 16:21
  • 3
    This didn't work for me unless my selector was $('body,html') Commented Jan 25, 2014 at 16:50
  • 32
    This solution works but the scroll bar disappear and create a 'bump' effect (under window os) when you apply this class to the body (for example)
    – Georgio
    Commented Jun 30, 2014 at 20:30
77

Here's a really basic way to do it:

window.onscroll = function () { window.scrollTo(0, 0); };

It's kind of jumpy in IE6.

10
  • 22
    Not really a disabling, more like a snap to default when the scroll is attempted. Commented Jan 22, 2011 at 19:34
  • 14
    @Marcus As good as it's going to get with an event that isn't cancelable. Commented Jan 22, 2011 at 19:35
  • 4
    Even though it doesn't disable it for real, it simulates it and that's good enough for me.
    – Chris Bier
    Commented Jun 5, 2012 at 18:40
  • 14
    IMHO - best answer here. Plus, you don't have to lock it to (0, 0), just use the current scroll position.
    – YemSalat
    Commented May 20, 2015 at 1:42
  • 8
    But how do we reenable it?
    – Cybernetic
    Commented Apr 23, 2019 at 18:43
74

The following solution is basic but pure JavaScript (no jQuery):

function disableScrolling(){
    var x=window.scrollX;
    var y=window.scrollY;
    window.onscroll=function(){window.scrollTo(x, y);};
}

function enableScrolling(){
    window.onscroll=function(){};
}
9
  • 4
    Jumpy in Safari 7.1 and IE 11. Newest Chrome, Firefox, Opera ok. Commented Dec 9, 2014 at 18:39
  • 3
    Still a tiny bit jumpy on newest Chrome Commented Nov 13, 2018 at 0:57
  • Working fine, In safari, chrome, but flickered in IE Commented Nov 14, 2018 at 6:00
  • If this solution not works for some browser, then that is browsers problem Commented Sep 12, 2019 at 8:57
  • 4
    You can set window.onscroll=null instead of adding an empty anonymous function, null is the initial value of window.onload
    – 27px
    Commented Feb 22, 2021 at 14:04
29

I'm sorry to answer an old post but I was looking for a solution and came across this question.

There are many workarounds for this issue to still display the scrollbar, like giving the container a 100% height and an overflow-y: scroll styling.

In my case I just created a div with a scrollbar which I display while adding overflow: hidden to the body:

function disableScroll() {
    document.getElementById('scrollbar').style.display = 'block';
    document.body.style.overflow = 'hidden';
}

The element scrollbar must have this styles:

overflow-y: scroll; top: 0; right: 0; display: none; height: 100%; position: fixed;

This shows a grey scrollbar, hope it helps future visitors.

1
  • 100% neat and simple trick, minimal JS no scroll events. Just target the element we need to disable scroll and set overflow to hidden. Been writing JS and CSS for almost 10 years and I did not thought of this! Then to re-enable scroll just toggle overflow to auto!
    – Dale Ryan
    Commented Jul 29, 2023 at 5:14
25

This solution will maintain the current scroll position whilst scrolling is disabled, unlike some which jump the user back to the top.

It's based on galambalazs' answer, but with support for touch devices, and refactored as a single object with jquery plugin wrapper.

Demo here.

On github here.

/**
 * $.disablescroll
 * Author: Josh Harrison - aloof.co
 *
 * Disables scroll events from mousewheels, touchmoves and keypresses.
 * Use while jQuery is animating the scroll position for a guaranteed super-smooth ride!
 */

;(function($) {

    "use strict";

    var instance, proto;

    function UserScrollDisabler($container, options) {
        // spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
        // left: 37, up: 38, right: 39, down: 40
        this.opts = $.extend({
            handleKeys : true,
            scrollEventKeys : [32, 33, 34, 35, 36, 37, 38, 39, 40]
        }, options);

        this.$container = $container;
        this.$document = $(document);
        this.lockToScrollPos = [0, 0];

        this.disable();
    }

    proto = UserScrollDisabler.prototype;

    proto.disable = function() {
        var t = this;

        t.lockToScrollPos = [
            t.$container.scrollLeft(),
            t.$container.scrollTop()
        ];

        t.$container.on(
            "mousewheel.disablescroll DOMMouseScroll.disablescroll touchmove.disablescroll",
            t._handleWheel
        );

        t.$container.on("scroll.disablescroll", function() {
            t._handleScrollbar.call(t);
        });

        if(t.opts.handleKeys) {
            t.$document.on("keydown.disablescroll", function(event) {
                t._handleKeydown.call(t, event);
            });
        }
    };

    proto.undo = function() {
        var t = this;
        t.$container.off(".disablescroll");
        if(t.opts.handleKeys) {
            t.$document.off(".disablescroll");
        }
    };

    proto._handleWheel = function(event) {
        event.preventDefault();
    };

    proto._handleScrollbar = function() {
        this.$container.scrollLeft(this.lockToScrollPos[0]);
        this.$container.scrollTop(this.lockToScrollPos[1]);
    };

    proto._handleKeydown = function(event) {
        for (var i = 0; i < this.opts.scrollEventKeys.length; i++) {
            if (event.keyCode === this.opts.scrollEventKeys[i]) {
                event.preventDefault();
                return;
            }
        }
    };


    // Plugin wrapper for object
    $.fn.disablescroll = function(method) {

        // If calling for the first time, instantiate the object and save
        // reference. The plugin can therefore only be instantiated once per
        // page. You can pass options object in through the method parameter.
        if( ! instance && (typeof method === "object" || ! method)) {
            instance = new UserScrollDisabler(this, method);
        }

        // Instance already created, and a method is being explicitly called,
        // e.g. .disablescroll('undo');
        else if(instance && instance[method]) {
            instance[method].call(instance);
        }

    };

    // Global access
    window.UserScrollDisabler = UserScrollDisabler;

})(jQuery);
15
  • Glad it's useful. NB I've edited with a link to this in jQuery plugin format. Commented Apr 25, 2014 at 12:08
  • Might help if the disable scroll button actually worked Commented May 22, 2014 at 12:05
  • @user1672694, it works here in Chrome. What's your browser and which demo page have you found the bug on? Any JS errors in the console? Commented May 23, 2014 at 11:36
  • On Chrome (38, Windows 7), I can still scroll by clicking and holding the middle-button down, then dragging.
    – Sethi
    Commented Oct 15, 2014 at 11:26
  • 1
    Please disregard, I found that binding it mousewheel worked a charm
    – adamj
    Commented Jul 24, 2015 at 7:09
23
var winX = null;
var winY = null;

window.addEventListener('scroll', function () {
    if (winX !== null && winY !== null) {
        window.scrollTo(winX, winY);
    }
});

function disableWindowScroll() {
    winX = window.scrollX;
    winY = window.scrollY;
}

function enableWindowScroll() {
    winX = null;
    winY = null;
}
1
  • for the type safety, I'd recommend to use negative numbers instead of null Commented Jun 25, 2021 at 10:17
9

I was looking out for a solution to this problem but was not satisfied with the any of the above solutions (as of writing this answer), so I came up with this solution..

CSS

.scrollDisabled {   
    position: fixed;
    margin-top: 0;// override by JS to use acc to curr $(window).scrollTop()
    width: 100%;
}

JS

var y_offsetWhenScrollDisabled=0;

function disableScrollOnBody(){
    y_offsetWhenScrollDisabled= $(window).scrollTop();
    $('body').addClass('scrollDisabled').css('margin-top', -y_offsetWhenScrollDisabled);
}
function enableScrollOnBody(){
    $('body').removeClass('scrollDisabled').css('margin-top', 0);
    $(window).scrollTop(y_offsetWhenScrollDisabled);
}
1
  • I found this worked for me if I added overflow-y: scroll to the .scrollDisabled style. Otherwise, there was a little jump as the scrollbar hid each time. Of course, that only works for me because my page it long enough to need a scrollbar even on the largest displays. Commented Feb 21, 2016 at 5:04
8

This answer suggests a solution for removing the "bump" that happens when overflow: hidden suggested in this solution is applied. Since an edit was declined, here it is:


To remove the "bump" that happens when overflow: hidden is applied, you could calculate the width of the scrollbar and substitute it with margin. Here's an example for the body element:

const bodyScrollControls = {
  scrollBarWidth: window.innerWidth - document.body.clientWidth,

  disable() {
    document.body.style.marginRight = `${this.scrollBarWidth}px`;
    document.body.style.overflowY = 'hidden';
  },
  enable() {
    document.body.style.marginRight = null;
    document.body.style.overflowY = null;
  },
};

If an element already has margin-right, getting existing one and adding scrollbar width to it shouldn't be a problem.

0
7

As of Chrome 56 and other modern browsers, you have to add passive:false to the addEventListener call to make preventDefault work. So I use this to stop scrolling on mobile:

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

function disableScroll(){
    document.body.addEventListener('touchmove', preventDefault, { passive: false });
}
function enableScroll(){
    document.body.removeEventListener('touchmove', preventDefault, { passive: false });
}
7

No, I wouldn't go with event handling because:

  • not all events are guaranteed to reach body,

  • selecting text and moving downwards actually scrolls the document,

  • if at the phase of event detaching sth goes wrong you are doomed.

I've bitten by this by making a copy-paste action with a hidden textarea and guess what, the page scroll whenever I make copy because internally I have to select the textarea before I call document.execCommand('copy').

Anyway that's the way I go, notice the setTimeout():

document.body.setAttribute('style','overflow:hidden;');
// do your thing...
setTimeout(function(){document.body.setAttribute('style','overflow:visible;');}, 500);

A momentum flashing exists as the scrollbars disappear momentarily but it's acceptable I thing.

1
  • I just had vertical scrolling on a table body (TBODY). stop: this.table.body.style.overflowY = 'hidden'; restart: this.table.body.style.overflowY = 'auto' Commented Jun 20, 2020 at 7:33
6

According to the galambalazs post I would add support for touch devices, allowing us to touch but no scroll up or down:

function disable_scroll() {
   ...
   document.ontouchmove = function(e){ 
        e.preventDefault(); 
   }
}

function enable_scroll() {
   ...
   document.ontouchmove = function(e){ 
     return true; 
   }
}
1
  • 5
    Are you sure that it is an answer not just a comment of other answer?
    – IvanH
    Commented Aug 23, 2013 at 13:55
5

Depending on what you want to achieve with the removed scroll you could just fix the element that you want to remove scroll from (on click, or whatever other trigger you'd like to temporarily deactivate scroll)

I was searching around for a "temp no scroll" solution and for my needs, this solved it

make a class

.fixed{
    position: fixed;
}

then with Jquery

var someTrigger = $('#trigger'); //a trigger button
var contentContainer = $('#content'); //element I want to temporarily remove scroll from

contentContainer.addClass('notfixed'); //make sure that the element has the "notfixed" class

//Something to trigger the fixed positioning. In this case we chose a button.
someTrigger.on('click', function(){

    if(contentContainer.hasClass('notfixed')){
        contentContainer.removeClass('notfixed').addClass('fixed');

    }else if(contentContainer.hasClass('fixed')){
        contentContainer.removeClass('fixed').addClass('notfixed');
    };
});

I found that this was a simple enough solution that works well on all browsers, and also makes for simple use on portable devices (i.e. iPhones, tablets etc). Since the element is temporarily fixed, there is no scroll :)

NOTE! Depending on the placement of your "contentContainer" element you might need to adjust it from the left. Which can easily be done by adding a css left value to that element when the fixed class is active

contentContainer.css({
    'left': $(window).width() - contentContainer.width()/2 //This would result in a value that is the windows entire width minus the element we want to "center" divided by two (since it's only pushed from one side)
});
5

You can do like this:

This way you save 'insignificant' memory and the elements that are with Position: fixed didn't move and thus don't road your design itself.

CSS (Using CSS makes your life and memory easier)

html[DisableScroll] {
    overflow-y: scroll;
}

html[DisableScroll] body {
    overflow-y: hidden;
    height: 100vh;
}

JS

var enableScroll = function () {
   document.documentElement
     .removeAttribute('DisableScroll');
}

e.g

//When you want to enable escroll just call this function;

var enableScroll = function () {
   document.documentElement
   .removeAttribute('DisableScroll');
}
 
 setTimeout(() => {
    enableScroll();
}, 2000);
*{
  margin: 0px;
  padding: 0px
}
body{
  height: 4000px;
  background: #141417
}

html[DisableScroll] {
    overflow-y: scroll
}

html[DisableScroll] body {
    overflow-y: hidden;
    height: 100vh;
}
body>p{
color: #FBFBFD
}

div{
  position: fixed;
  left: 0;
  right: 0;
  margin: auto;
  width: 270px;
  background: #FBFBFD;
  color: #141417;
  text-align: center
} 
<!DOCTYPE html>
 <html lang="en" DisableScroll>
 <head>
     <meta charset="UTF-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Document</title>
 </head>
 <body> 
    <div>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    </div>
     <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
    <p>@@@@</p><br>
 </body>
 </html>

4

I'm using showModalDialog, for showing secondary page as modal dialog.

to hide main window scrollbars:

document.body.style.overflow = "hidden";

and when closing modal dialog, showing main window scrollbars:

document.body.style.overflow = "scroll";

to access elements in main window from dialog:

parent.document.getElementById('dialog-close').click();

just for anybody searching about showModalDialog:(after line 29 of original code)

document.getElementById('dialog-body').contentWindow.dialogArguments = arg;
document.body.style.overflow = "hidden";//****
document.getElementById('dialog-close').addEventListener('click', function(e) {
    e.preventDefault();
    document.body.style.overflow = "scroll";//****
    dialog.close();
});
1
  • This worked for me in React where jQuery is non existent and where React does not have access to manage the state of the body tag.
    – Jon
    Commented Nov 22, 2016 at 16:35
4

Another solution:

body {
    overflow-y: scroll;
    width: 100%;
    margin: 0 auto;
}

This way you always have a vertical scrollbar, but as most of my content is longer than the viewport, this is ok for me. Content is centered with a separate div, but without setting margin again in body my content would stay at the left.

These are the two function I use to show my popup/modal:

var popup_bodyTop = 0;
var popup_bodyLeft = 0;

function popupShow(id)
{
    $('#'+ id).effect('fade');
    $('#popup-overlay').effect('fade');

    // remember current scroll-position
    // because when setting/unsetting position: fixed to body
    // the body would scroll to 0,0
    popup_bodyLeft = $(document).scrollLeft();
    popup_bodyTop  = $(document).scrollTop();

    // invert position
    var x = - popup_bodyLeft;
    var y = - popup_bodyTop;

    $('body').css('position', 'fixed');
    $('body').css('top', y.toString() +'px');
    $('body').css('left', x.toString() +'px');
}

function popupHide(id)
{
    $('#'+ id).effect('fade');
    $('#popup-overlay').effect('fade');
    $('body').css('position', '');
    $('html, body').scrollTop(popup_bodyTop);
    $('html, body').scrollLeft(popup_bodyLeft);
}

Result: non scrollable background and no re-positioning of the content because of the left scrollbar. Tested with current FF, Chrome and IE 10.

1
  • This worked for me and the problem of scrolling to the top after using position:fixed. Thank u! Commented Feb 16, 2018 at 9:32
4

This is the simplest solution I got so far. And believe me I tried all the others and this is the easiest one. It works great on Windows devices, which pushes the page from the right to have room for the system scrollbar and IOS devices which don't require space for their scrollbars in the browsers. So by using this you wont need to add padding on the right so the page doesn't flicker when you hide the overflow of the body or html with css.

The solution is pretty simple if you think about it. The idea is to give the window.scrollTop() the same exact position at the moment that a popup is opened. Also change that position when the window resizes ( as the scroll position changes once that happens ).

So here we go...

First lets create the variable that will let you know that the popup is open and call it stopWindowScroll. If we don't do this then you'll get an error of an undefined variable on your page and set it to 0 - as not active.

$(document).ready(function(){
    stopWindowScroll = 0;
});

Now lets make the open popup function witch can be any function in your code that triggers whatever popup you are using as a plugin or custom. In this case it will be a simple custom popup with a simple document on click function.

$(document).on('click','.open-popup', function(){
    // Saving the scroll position once opening the popup.
    stopWindowScrollPosition = $(window).scrollTop();
    // Setting the stopWindowScroll to 1 to know the popup is open.
    stopWindowScroll = 1;
    // Displaying your popup.
    $('.your-popup').fadeIn(300);
});

So the next thing we do is create the close popup function, which I repeat again can be any function you already have created or are using in a plugin. The important thing is that we need those 2 functions to set the stopWindowScroll variable to 1 or 0 to know when it's open or closed.

$(document).on('click','.open-popup', function(){
    // Setting the stopWindowScroll to 0 to know the popup is closed.
    stopWindowScroll = 0;
    // Hiding your popup
    $('.your-popup').fadeOut(300);
});

Then lets create the window.scroll function so we can prevent the scrolling once the stopWindowScroll mentioned above is set to 1 - as active.

$(window).scroll(function(){
    if(stopWindowScroll == 1) {
         // Giving the window scrollTop() function the position on which
         // the popup was opened, this way it will stay in its place.
         $(window).scrollTop(stopWindowScrollPosition);
    }
});

Thats it. No CSS required for this to work except your own styles for the page. This worked like a charm for me and I hope it helps you and others.

Here is a working example on JSFiddle:

JS Fiddle Example

Let me know if this helped. Regards.

4

I found that changing the style of body was not necessary.

The only thing we need is to prevent the whole document (html element) from having a y scrolling.

We can create and destroy a style sheet with Javascript to do that. Here's how I do it:

https://jsfiddle.net/3os72ryk/

let scroll_style_element;

function disable_scrolling(){
    
  // Create a style sheet we will only use to disable scrolling :
  scroll_style_element = document.createElement('style');
  document.head.appendChild(scroll_style_element);
  const scroll_style_sheet = scroll_style_element.sheet;
    
  scroll_style_sheet.insertRule('html{height:100%;overflow-y:hidden;}', scroll_style_sheet.cssRules.length);
}

function enable_scrolling(){
  if( scroll_style_element ) document.head.removeChild(scroll_style_element);
}

Very interested to know if anyone finds something wrong with this approach, so please comment below if you do.

1
  • Implemented on react application successfully! Thanks. Commented Apr 1, 2023 at 20:46
3

How about this? (If you're using jQuery)

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

window.onscroll = function() {
    var overlay = $body.children(".ui-widget-overlay").first();

    // Check if the overlay is visible and restore the previous scroll state
    if (overlay.is(":visible")) {
        var scrollPos = $body.data("scroll-pos") || { x: 0, y: 0 };
        window.scrollTo(scrollPos.x, scrollPos.y);
    }
    else {
        // Just store the scroll state
        $body.data("scroll-pos", { x: $window.scrollLeft(), y: $window.scrollTop() });
    }
};
1
  • a bit jumpy, but this works for IE 7 (client uses it). other solutions do not.
    – niki b
    Commented Apr 22, 2014 at 19:40
3

Cancelling the event's as in the accepted answer is a horrible method in my opinion :/

Instead I used position: fixed; top: -scrollTop(); below.

Demo: https://jsfiddle.net/w9w9hthy/5/

From my jQuery popup project: https://github.com/seahorsepip/jPopup

//Freeze page content scrolling
function freeze() {
    if($("html").css("position") != "fixed") {
        var top = $("html").scrollTop() ? $("html").scrollTop() : $("body").scrollTop();
        if(window.innerWidth > $("html").width()) {
            $("html").css("overflow-y", "scroll");
        }
        $("html").css({"width": "100%", "height": "100%", "position": "fixed", "top": -top});
    }
}

//Unfreeze page content scrolling
function unfreeze() {
    if($("html").css("position") == "fixed") {
        $("html").css("position", "static");
        $("html, body").scrollTop(-parseInt($("html").css("top")));
        $("html").css({"position": "", "width": "", "height": "", "top": "", "overflow-y": ""});
    }
}

This code takes, width, height, scrollbar and pagejump issues into consideration.

Possible issues resolved with above code:

  • width, when setting position fixed the html element width can be smaller then 100%
  • height, same as above
  • scrollbar, when setting position fixed the page content no longer has a scrollbar even when it had a scrollbar before resulting in a horizontal pagejump
  • pagejump, when setting position fixed the page scrollTop is no longer effective resulting in a vertical pagejump

If anyone has any improvements to above page freeze/unfreeze code let me know so I can add those improvements to my project.

3

The simplest method is:

$("body").css("overflow", "hidden"); // Remove the scroll bar temporarily

To undo it:

$("body").css("overflow", "auto");

Easy to implement, but the only downside is:

  • The page will jump a bit to the left if it is center-aligned (horizontally).

This is due to the scroll bar being removed, and the viewport becoming a bit wider.

5
  • 1
    that will reset the scroll position Commented Aug 21, 2018 at 6:13
  • @AngelDavidCalderaroPacciott No, the scroll position will remain the same height/distance.
    – Daan
    Commented Aug 21, 2018 at 7:31
  • @Daan it does reset the scroll position on Chrome
    – Tom
    Commented Aug 29, 2019 at 22:26
  • @Tom I just checked it, it only does it on some occassions (when the body height isn't relative to its children). Please try changing body to html instead.
    – Daan
    Commented Aug 30, 2019 at 7:11
  • I bet you didn't check your solution in Iphone cause overflow:hidden doesn't work in there
    – Shuvo
    Commented Jun 4, 2020 at 9:17
3

Here is my solution to stop the scroll (no jQuery). I use it to disable the scroll when the side menu appears.

<button onClick="noscroll()" style="position:fixed; padding: 8px 16px;">Disable/Enable scroll</button>
<script>
var noscroll_var;
function noscroll(){
  if(noscroll_var){
    document.getElementsByTagName("html")[0].style.overflowY = "";
    document.body.style.paddingRight = "0";
    noscroll_var = false
  }else{
    document.getElementsByTagName("html")[0].setAttribute('style', 'overflow-y: hidden !important');
    document.body.style.paddingRight = "17px";
    noscroll_var = true
  }
}/*noscroll()*/
</script>

<!-- Just to fill the page -->
<script>
  for(var i=0; i <= 80; i++){
    document.write(i + "<hr>")
  }
</script>

I put 17px of padding-right to compensate for the disappearance of the scroll bar. But this is also problematic, mostly for mobile browsers. Solved by getting the bar width according to this.

All together in this Pen.

3

To prevent the jump, this is what I used

export function toggleBodyScroll(disable) {
  if (!window.tempScrollTop) {
    window.tempScrollTop = window.pageYOffset; 
    // save the current position in a global variable so I can access again later

  }
  if (disable) {
    document.body.classList.add('disable-scroll');
    document.body.style.top = `-${window.tempScrollTop}px`;
  } else {
    document.body.classList.remove('disable-scroll');
    document.body.style.top = `0px`;
    window.scrollTo({top: window.tempScrollTop});
    window.tempScrollTop = 0;
  }
}

and in my css

.disable-scroll {
  height: 100%;
  overflow: hidden;
  width: 100%;
  position: fixed;
}

3

Toggle the overflowY with a Javascript function at the same time you toggle your mobile menu's visibility. Like this for example:

function handleClickMobileMenu() {
  document.body.style.overflowY = isMobileMenuOpen ? "hidden" : "scroll";
  //...
}

Call the function when you toggle the mobile menu on and off. Best use case is when your mobile menu is taking full viewport area.

2

Building on Cheyenne Forbes' answer, and one I found here via fcalderan: Just disable scroll not hide it? and to fix Hallodom's issue of the scrollbar disappearing

CSS:

.preventscroll{
    position: fixed;
    overflow-y:scroll;
}

JS:

whatever.onclick = function(){
    $('body').addClass('preventscroll');
}
whatevertoclose.onclick = function(){
    $('body').removeClass('preventscroll');
}

This code does jump you to the top of the page, but I think that fcalderan's code has a workaround.

2

I know this is an old question, but I had to do something very similar, and after some time looking for an answer and trying different approaches, I ended up using a very easy solution.

My problem was very similar, almost identical, the only difference is I didn't have to actually show the scroll bar - I just had to make sure its width would still be used, so the page's width would not change while my overlay was displayed.

When I start sliding my overlay into the screen, I do:

$('body').addClass('stop-scrolling').css('margin-right', 8);

and after I slide my overlay off the screen I do:

$('body').removeClass('stop-scrolling').css('margin-right', 0);

IMPORTANT: this works perfectly because my overlay is positioned absolute, right: 0px when visible.

2

I have the same problem, below is the way I handle it.

/* file.js */
var body = document.getElementsByTagName('body')[0];
//if window dont scroll
body.classList.add("no-scroll");
//if window scroll
body.classList.remove("no-scroll");

/* file.css */
.no-scroll{
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

hope this help.

0
2

I have similar issue on touch devices. Adding "touch-action: none" to the element resolved the issue.

For more information. Check this out:-

https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action

2

This code will work on Chrome 56 and further (original answer doesn't work on Chrome anymore).

Use DomUtils.enableScroll() to enable scrolling.

Use DomUtils.disableScroll() to disable scrolling.

class DomUtils {
  // left: 37, up: 38, right: 39, down: 40,
  // spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
  static keys = { 37: 1, 38: 1, 39: 1, 40: 1 };

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

  static preventDefaultForScrollKeys(e) {
    if (DomUtils.keys[e.keyCode]) {
      DomUtils.preventDefault(e);
      return false;
    }
  }

  static disableScroll() {
    document.addEventListener('wheel', DomUtils.preventDefault, {
      passive: false,
    }); // Disable scrolling in Chrome
    document.addEventListener('keydown', DomUtils.preventDefaultForScrollKeys, {
      passive: false,
    });
  }

  static enableScroll() {
    document.removeEventListener('wheel', DomUtils.preventDefault, {
      passive: false,
    }); // Enable scrolling in Chrome
    document.removeEventListener(
      'keydown',
      DomUtils.preventDefaultForScrollKeys,
      {
        passive: false,
      }
    ); // Enable scrolling in Chrome
  }
}
2

i use this simple trick here:

.no-scroll{
  overflow: hidden;
}

let toggle_scrolling_state = () => {
   element.classList.toggle("no-scroll");
}

and then call the function when you want to stop scrolling on a event or ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.