How to block page scrolling without hiding the bar?

Asked

Viewed 61 times

0

How do I make it so that when the user tries to scroll the page, there is no effect, but without hiding the scroll bar?

All I know is overflow: hidden , but it hides the bar.

  • The question is not clear enough. How would you see the content if you can’t scroll the page?

  • @Lipespry It’s only for when opening a lightbox...

1 answer

0

I found that code Javascript in the English stack: How to disable scrolling temporarily?

// 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 = e || window.event;
  if (e.preventDefault)
      e.preventDefault();
  e.returnValue = false;  
}

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

function disableScroll() {
  if (window.addEventListener) // older FF
      window.addEventListener('DOMMouseScroll', preventDefault, false);
  window.onwheel = preventDefault; // modern standard
  window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
  window.ontouchmove  = preventDefault; // mobile
  document.onkeydown  = preventDefaultForScrollKeys;
}

function enableScroll() {
    if (window.removeEventListener)
        window.removeEventListener('DOMMouseScroll', preventDefault, false);
    window.onmousewheel = document.onmousewheel = null; 
    window.onwheel = null; 
    window.ontouchmove = null;  
    document.onkeydown = null;  
}

Just make a call from the function in your own code.

Credits to: galambalazs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.