Reputation: 2223
I'm working with a div sitting above another div. When I scroll the div that sits above the other and reach the bottom, it scrolls the entire body. This is hard to explain so I made a fiddle to demonstrate the effect: http://jsfiddle.net/2Ydr4/
HTML:
<div class="body">
<div class="above">
<!-- Content in here that is longer than the height -->
</div>
</div>
CSS:
.above {
width: 300px;
height: 200px;
overflow-y: scroll;
background: red;
z-index: 10;
position: fixed;
}
My question is: how do I prevent the body scrolling when the floating div is scrolled to the bottom or top? I'm sure it's something really obvious that I'm missing. Thanks!
EDIT: I should probably have mentioned that the target device for this was an iPad. I've tried adding body {overflow: hidden}
conditionally as suggested below, and while this solves the problem on a desktop browser, it still seems to persist on a touch-based browser.
Upvotes: 4
Views: 2665
Reputation: 251
Desktop
That's how scrolling works. What you will need to do is remove the body's scroll property temporarily or by the users action.
For example you could disable the body's scroll when the user hovers over the floating div by using...
body{overflow:hidden}
and then re-enable it when you hover off the floating div by using..
body{overflow:auto}
Mobile
On mobile devices you will need to use touch events. I haven't tried this but in theory this should work.
var $body = document.querySelector('.body'),
$above = document.querySelector('.above');
$above.addEventListener('ontouchstart', onAboveStart, false);
$body.addEventListener('ontouchstart', onBodyStart, false);
function onAboveStart()
{
$body.addEventListener('ontouchmove', function(e) {e.preventDefault()}, false);
}
function onBodyStart()
{
$body.removeEventListener('ontouchmove', function(e) {e.preventDefault()});
}
Upvotes: 2