All I'm trying to do is to call a function when a DIV
is scrolled.For simplicity sake Im not specifying anything else. Also I am only looking at DOM compliant browsers like Chrome, Safari (not IE).
MY problem is that the scroll handler never gets called. If I replace the scroll
to click
, it works when I click. Somehow the scroll is not working.
Please note: I cannot use jQuery :(
Here is my code:
HTML:
<div id="test">--long content--</div>
JS:
function myFunc() { console.log('in myFunc'); } var objTable = document.getElementById("test"); objTable.addEventListener("scroll", function () { myFunc(); }, false);
FIDDLE:
http://jsfiddle.net/yymg5/7/
How it works: First, set the scrolling flag to false . If the scroll event fires set the scrolling flag to true inside the scroll event handler. Then, execute the scroll event handler using the setInterval() every 300 milliseconds if the scroll events have been fired.
The scroll event fires when the document view has been scrolled. For element scrolling, see Element: scroll event . Note: In iOS UIWebViews, scroll events are not fired while scrolling is taking place; they are only fired after the scrolling has completed. See Bootstrap issue #16202.
To scroll the page with JavaScript, its DOM must be fully built. For instance, if we try to scroll the page with a script in <head> , it won't work. Regular elements can be scrolled by changing scrollTop/scrollLeft . We can do the same for the page using document.
The scroll event does not bubble up. Although the event does not bubble, browsers fire a scroll event on both document and window when the user scrolls the entire page.
This is because the window is scrolling not the div. Try changing your element listener to the parent of the div (in this case the window) like this.
window.addEventListener("scroll", function () { myFunc(); }, false);
i had the similar issue in my case. This code is correct, already answered by Undefined
window.addEventListener("scroll", function () { myFunc(); }, false);
but it was not working because,
scroll event wasn't firing. since my body was scrolling instead of documentElement.
I just removed height: 100%
from my body tag and then scroll event started firing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With