How to disable and enable the scroll in website(Java Script)

In this section we can see how we can disable and enable scrolling option in an ecommerce website using javascript function.

First of all we have to set up a block of code in the respective page.

// PREVENT DEFAULT HANDLER
function preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault) {
    e.preventDefault();
  }
  e.returnValue = false;
}
// PREVENT SCROLL KEYS
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
// left: 37, up: 38, right: 39, down: 40,
// (Source: http://stackoverflow.com/a/4770179)
function keydown(e) {
  var keys = [32,33,34,35,36,37,38,39,40];
  for (var i = keys.length; i–;) {
    if (e.keyCode === keys[i]) {
      preventDefault(e);
      return;
    }
  }
}
// PREVENT MOUSE WHEEL
function wheel(event) {
  event.preventDefault();
  event.stopPropagation();
  return false;
}
// DISABLE SCROLL
function disable_scroll() {
  if (document.addEventListener) {
    document.addEventListener(‘wheel’, wheel,{ passive: false });
    document.addEventListener(‘mousewheel’, wheel, { passive: false });
    document.addEventListener(‘DOMMouseScroll’, wheel, { passive: false });
  }
  else {
    document.attachEvent(‘onmousewheel’, wheel);
  }
  document.onmousewheel = document.onmousewheel = wheel;
  document.onkeydown = keydown;
  
  x = window.pageXOffset || document.documentElement.scrollLeft,
  y = window.pageYOffset || document.documentElement.scrollTop,
  window.onscroll = function() {
    window.scrollTo(x, y);
  };
  // document.body.style.overflow = ‘hidden’; // CSS
  disable_scroll_mobile();
}
// ENABLE SCROLL
function enable_scroll() {
  if (document.removeEventListener) {
    document.removeEventListener(‘wheel’, wheel, { passive: false });
    document.removeEventListener(‘mousewheel’, wheel, { passive: false });
    document.removeEventListener(‘DOMMouseScroll’, wheel, { passive: false });
  }
  document.onmousewheel = document.onmousewheel = document.onkeydown = null;
  window.onscroll = function() {};
  // document.body.style.overflow = ‘auto’; // CSS
  enable_scroll_mobile();
}

// MOBILE
function disable_scroll_mobile(){
  document.addEventListener(‘touchmove’, preventDefault, { passive: false });
}
function enable_scroll_mobile(){
  document.removeEventListener(‘touchmove’, preventDefault, { passive: false });
}

Call the function disable_scroll(); in place you need to disable scrolling and enable_scroll() where you need to enable. These methods are really use full when you are creating a pop up or something like that and make scrolling option disable while the pop up appears

Leave a comment

Your email address will not be published. Required fields are marked *