Javascript Scroll Handler not firing

痞子三分冷 提交于 2019-12-12 09:31:25

问题


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/


回答1:


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);



回答2:


i had the similar issue in my case. This code is correct but was not working because,

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

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.




回答3:


I have similar issue. But in my case, I have a height: 100% on my body. Since, I just wanted to apply the scroll event in a special div only.

Then, this fixed the issue:

document.querySelector('#myDiv').addEventListener('scroll', () => { console.log('scroll event fired!') });



来源:https://stackoverflow.com/questions/15275969/javascript-scroll-handler-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!