How to programmatically disable page scrolling with jQuery

Hailwood picture Hailwood · Sep 7, 2010 · Viewed 435.7k times · Source

Using jQuery, I would like to disable scrolling of the body:

My idea is to:

  1. Set body{ overflow: hidden;}
  2. Capture the current scrollTop();/scrollLeft()
  3. Bind to the body scroll event, set scrollTop/scrollLeft to the captured value.

Is there a better way?


Update:

Please see my example, and a reason why, at http://jsbin.com/ikuma4/2/edit

I am aware someone will be thinking "why does he not just use position: fixed on the panel?".

Please do not suggest this as I have other reasons.

Answer

gitaarik picture gitaarik · Jun 25, 2013

This will completely disable scrolling:

$('html, body').css({
    overflow: 'hidden',
    height: '100%'
});

To restore:

$('html, body').css({
    overflow: 'auto',
    height: 'auto'
});

Tested it on Firefox and Chrome.