Reputation: 21
I'm trying to execute a Javascript function whenever a user scrolls a page.
I've tried:
<body onscroll="myScrollFunction()">
and this works fine in Firefox but not IE.
I also tried:
window.onscroll = "myScrollFunction()";
but this seems to only perform the function once, similar to an onload event, but further scrolls do not fire the event. My doctype is set to strict; not sure if this makes a difference or not.
How can I get this to work across all browsers?
What I'm trying to accomplish is a way to prevent users from scrolling once a modal is displayed. I'd rather not use
overflow:hidden
because the document shifts slightly when the modal is displayed (to compensate for the scrollbar), so I figured I could capture the scroll function and lock it to the top of the page whenever the modal is displayed. If there is an easier way to do this, please let me know.
Upvotes: 1
Views: 2151
Reputation: 144912
Set the <body>
's overflow
to hidden
while your lightbox is open.
$('body').css('overflow','hidden');
...then return to normal when it closes:
$('body').css('overflow','auto');
Upvotes: 0
Reputation: 6562
Instead of
window.onscroll = myScrollFunction();
which assigns the result of the myScrollFunction()
to the onscroll handler, you want
window.onscroll = myScrollFunction;
which assigns the function itself, and will therefore be called on each scroll.
Upvotes: 4
Reputation: 413737
I suggest that instead of doing that, you just give your modal dialog position: fixed;
which will fix it to the viewport instead of the page.
Upvotes: 1