tags:

views:

154

answers:

1

Hi there.

Using jquery I would like to disable scrolling (of the body)

my idea is to
a: set body{ overflow: hidden;}
b: capture current scrollTop();/scrollLeft()
c: bind to the body scroll event, set scrollTop/scrollLeft to the captured value.

is there a better way?

Melodramatically = [auto spell check fail :/]


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.

+1  A: 

The only way I've found to do this is similar to what you described:

  1. Grab current scroll position (don't forget horizontal axis!).
  2. Set overflow to hidden (probably want to retain previous overflow value).
  3. Scroll document to stored scroll position with scrollTo().

Then when you're ready to allow scrolling again, undo all that.

Edit: no reason I can't give you the code since I went to the trouble to dig it up...

      // lock scroll position, but retain settings for later
      var scrollPosition = [
        self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
        self.pageYOffset || document.documentElement.scrollTop  || document.body.scrollTop
      ];
      var html = jQuery('html'); // it would make more sense to apply this to body, but IE7 won't have that
      html.data('scroll-position', scrollPosition);
      html.data('previous-overflow', html.css('overflow'));
      html.css('overflow', 'hidden');
      window.scrollTo(scrollPosition[0], scrollPosition[1]);


      // un-lock scroll position
      var html = jQuery('html');
      var scrollPosition = html.data('scroll-position');
      html.css('overflow', html.data('previous-overflow'));
      window.scrollTo(scrollPosition[0], scrollPosition[1])
tfe
please see http://jsbin.com/ikuma4/2/edit and explain any reason to me that yours is better? am i missing something (i ask as i can not see any reason for the length of your answer as compared to my example)
Hailwood
Your approach doesn't work in IE7. I tried that first too. The problem is that it doesn't react to the scroll event quickly enough. It lets the document scroll, then snaps it back when your JS resets the scroll position back where you want it.
tfe
Also, if body had an overflow of anything other than `auto`, it would be overwritten. I needed to preserve the existing setting, so that adds some overhead too.
tfe