Javascript scroll handler not working

All I'm trying to do is call the function when the DIV scrolls. For the sake of simplicity, I do not define anything. Also, I look only at DOM-compatible browsers such as Chrome, Safari (not IE).

My problem is that the scroll handler is never called. If I replace scroll with click , it works when I click. Somehow the scroll does not work.

Please note: I can not 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/

+14
source share
2 answers

This is because no div is scrolling in the window. Try changing the element listener to the parent div element (in this case, a window), for example this .

 window.addEventListener("scroll", function () { myFunc(); }, false); 
+22
source

I had a similar problem in my case. This code is correct, but did not work because,

 window.addEventListener("scroll", function () { myFunc(); }, false); 

the scroll event did not fire. since my body was scrolling instead of documentElement.

I just removed height: 100% from my body tag, and then the scroll event started.

+5
source

All Articles