Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Scroll Handler not firing

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/

like image 564
Sajjan Sarkar Avatar asked Mar 07 '13 16:03

Sajjan Sarkar


People also ask

How do you fire scroll an event?

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.

How often does scroll event fire?

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.

How do you scroll in JavaScript?

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.

Does scroll event bubble?

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.


2 Answers

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); 
like image 62
Undefined Avatar answered Sep 17 '22 17:09

Undefined


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.

like image 37
Vikramaditya Avatar answered Sep 18 '22 17:09

Vikramaditya