Patrick Schomburg Patrick Schomburg - 3 months ago 16
Javascript Question

Dont scroll the body when mouse is over child element

I'm trying to stop my main page from scrolling when the user hits the bottom of two specific sections of a page using the following code, but it's stopping the mouse wheel from working over those divs at all.

var scroller = document.querySelector('#Filters');

scroller.addEventListener('wheel', listener);

function listener(event)
{
var elem = event.currentTarget;

if ((event.deltaY < 0 && elem.scrollTop === 0) ||
(event.deltaY > 0 && elem.offsetHeight + elem.scrollTop >= elem.scrollHeight))
{
event.preventDefault();
}
else if ((event.deltaX < 0 && elem.scrollLeft === 0) ||
(event.deltaX > 0 && elem.offsetWidth + elem.scrollLeft >= elem.scrollWidth))
{
event.preventDefault();
}
}

Answer

You can use a more efficient solution than recalculating the scroll in js, disabling the body scrolling when scrolling the child element.

HTML:

<div onmouseover="disableScroll();" onmouseout="enableScroll();">
    content
</div>

JS:

var body = document.getElementsByTagName('body')[0];
function enableScroll() {
    body.style.overflowY = 'auto';
}
function disableScroll() {
    body.style.overflowY = 'hidden';
}
Comments