Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overflow scrolling div underneath

Tags:

html

css

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.

like image 757
samturner Avatar asked Aug 09 '26 03:08

samturner


1 Answers

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()});
}
like image 126
synapze Avatar answered Aug 10 '26 18:08

synapze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!