0

I want to disable the body from scrolling when a div is in the foreground. The div is scrollable and I don't want the body to scroll along with it. I accomplished this in a browser but it doesn't work in mobile. What do I need to change from when the div is open:

$('body').css('overflow', 'hidden');

to when the div is closed:

$('body').css('overflow', 'auto');

But as I said, it doesn't work in mobile (iOS or Android). I tried epreventdefault() also and that didn't help. The css gets changed with onclick events...

user2025469
  • 1,531
  • 2
  • 14
  • 26
  • You're missing a `'` in `auto'`. Try to put a _parent_ div - `...
    ...
    `, and use `$('.main').css('overflow', 'hidden');`.
    – Vucko Jul 29 '13 at 17:57
  • That didn't work either, and it stopped working in the browser also. Can you please refer to my other post on SO where I have the entire code? I tried using iScroll but it didn't work. Now I'm trying with plain CSS. http://stackoverflow.com/questions/17927179/iscroll-a-dynamically-filled-div-only-without-scrolling-main-page-also – user2025469 Jul 29 '13 at 18:08
  • 1
    Then try with [niceScroll](http://areaaperta.com/nicescroll/). – Vucko Jul 29 '13 at 18:13
  • Will niceScroll work with dynamically added content? iScroll needed refreshing and using the settimeout... – user2025469 Jul 29 '13 at 18:32
  • 1
    See [this](https://github.com/inuyaksa/jquery.nicescroll/wiki/Nicescroll-with-dynamic-content) and [this](http://stackoverflow.com/questions/11862656/jquery-nice-scroll-not-working) – Vucko Jul 30 '13 at 05:43
  • Thanks Vucko. It looks like it could work...only problem is I'm not using jQuery. I'm building this for mobile and trying to limit big libraries. I'm using Zepto and niceScroll only works with jQuery. Great advice but I'll keep looking... – user2025469 Jul 30 '13 at 11:22

2 Answers2

1

this worked for me:

document.body.scroll = "no";
document.body.style.overflow = 'hidden';
document.height = window.innerHeight;

document.body.addEventListener('touchmove', function(e){ e.preventDefault(); });
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
reza
  • 11
  • 3
1

After facing a similar problem with mobile scrolling causing a mess with my scrollable divs and unwanted scrolling body, the touchmove listener event is the key. A couple caveats I came across tho that I had to figure out. One, in order to remove the event listener, and give your body back its scrolling (as was my case with a menu that slide in from right and covered the entire window) you have to name the function that gets included iun the event listener, that way you can call the same function to be removed with removeEventListener.

var prevent = function(e){ 
    e.preventDefault();
};

function menuOpen(){
    document.body.addEventListener('touchmove', prevent);
};

function menuClose(){
    document.body.removeEventListener('touchmove', prevent);
};