ChatGPT解决这个技术问题 Extra ChatGPT

How to disable scrolling temporarily?

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.

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.

g
gblazex

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


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 :)
You can add 32 (space) to the disabled keys array (show in the code comments).
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 ;)
The scrollbar is not disabled.
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.
M
MusikAnimal

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')

For mobile devices, you'll need to handle the touchmove event:

$('body').bind('touchmove', function(e){e.preventDefault()})

And unbind to re-enable scrolling. Tested in iOS6 and Android 2.3.3

$('body').unbind('touchmove')

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.
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.
While this solution does work, it has the (potentially) undesirable effect of scrolling back to the top of the page.
This didn't work for me unless my selector was $('body,html')
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)
s
sdleihssirhc

Here's a really basic way to do it:

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

It's kind of jumpy in IE6.


Not really a disabling, more like a snap to default when the scroll is attempted.
@Marcus As good as it's going to get with an event that isn't cancelable.
Even though it doesn't disable it for real, it simulates it and that's good enough for me.
IMHO - best answer here. Plus, you don't have to lock it to (0, 0), just use the current scroll position.
But how do we reenable it?
M
Mohammad Anini

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(){};
}

Jumpy in Safari 7.1 and IE 11. Newest Chrome, Firefox, Opera ok.
Still a tiny bit jumpy on newest Chrome
Working fine, In safari, chrome, but flickered in IE
If this solution not works for some browser, then that is browsers problem
You can set window.onscroll=null instead of adding an empty anonymous function, null is the initial value of window.onload
C
Community

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);

Glad it's useful. NB I've edited with a link to this in jQuery plugin format.
Might help if the disable scroll button actually worked
@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?
On Chrome (38, Windows 7), I can still scroll by clicking and holding the middle-button down, then dragging.
Please disregard, I found that binding it mousewheel worked a charm
u
u01jmg3

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.


V
Văn Quyết
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;
}

This is the best solution here.
@jfunk agree, simple and concise, small code, perfect. Thank you
for the type safety, I'd recommend to use negative numbers instead of null
R
Rajat Gupta

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);
}

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.
H
Hokascha

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 });
}

c
centurian

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.


I just had vertical scrolling on a table body (TBODY). stop: this.table.body.style.overflowY = 'hidden'; restart: this.table.body.style.overflowY = 'auto'
j
jvalen

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; 
   }
}

Are you sure that it is an answer not just a comment of other answer?
a
axelra82

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)
});

Z
Zolfaghari

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();
});

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.
u
u01jmg3

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.


This worked for me and the problem of scrolling to the top after using position:fixed. Thank u!
A
Architect

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.


G
Giulia

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 } Document

@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@


@@@@



D
Dan

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() });
    }
};

a bit jumpy, but this works for IE 7 (client uses it). other solutions do not.
u
u01jmg3

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.


D
Daan

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.


that will reset the scroll position
@AngelDavidCalderaroPacciott No, the scroll position will remain the same height/distance.
@Daan it does reset the scroll position on Chrome
@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.
I bet you didn't check your solution in Iphone cause overflow:hidden doesn't work in there
S
Stephen Rauch

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

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.


M
Milad

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;
}


c
cotneit

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.


This was by far the easiest solution out of them all. Thank you. You saved my day :D
Q
Quibble

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.


k
kyun

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.


R
Robert

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.


P
PerrierCitror

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
  }
}

m
modex98

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 ...


G
Gurpreet

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


K
Kareem

Store scroll length in a global variable and restore it when needed!

var sctollTop_length = 0;

function scroll_pause(){
  sctollTop_length = $(window).scrollTop();
  $("body").css("overflow", "hidden");
}

function scroll_resume(){
  $("body").css("overflow", "auto");
  $(window).scrollTop(sctollTop_length);
}

p
pennstump

I found this answer on another site:

Disable scroll:

$( ".popup").live({
    popupbeforeposition: function(event, ui) {
    $("body").on("touchmove", false);
}
});

After close popup release scroll:

$( ".popup" ).live({
    popupafterclose: function(event, ui) {
    $("body").unbind("touchmove");
}
});

That only seems to stop touch scrolling, but the mouse scrolling, arrow keys, page up and down keys, etc will still work. -1
These 'events' are for touch scrolling, just substitute whatever events you need.
also, this seems to be used in some other very specific situation. popupbeforeposition? What is that supposed to be for? What does this have to do with temporarily disabling scrolling? At least make it relevant to this situation. It looks like you copied this directly from a website.