Cross-browser method to capture scroll events (or an easier way to temporarily disable scrolling)

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


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.



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.

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.

Set the <body>'s overflow to hidden while your lightbox is open.


...then return to normal when it closes:


Need Your Help

How do I implement task prioritization using an ExecutorService in Java 5?

java multithreading concurrency

I am implementing a thread pooling mechanism in which I'd like to execute tasks of varying priorities. I'd like to have a nice mechanism whereby I can submit a high priority task to the service an...

I want to know how to get how many people views your page?

django url pageviews

For one url, I want to how to detect how many times this url has been viewed?