Onscroll Function Is Not Working for Chrome
The Below Code Is Working Fine for Firefox Browser. But, Not Chrome. What Is the Issue in Below Code? Window. Onload = Function() { Document. Body. Onscroll =...
The below code is working fine for Firefox browser. But, not chrome. What is the issue in below code ?
window.onload = function()
{
document.body.onscroll = Test.callFn;
}
var Test = new function()
{
this.callFn = function()
{
console.log("Calling this function");
}
}
Thanks
7 Answers
I had similar problem today. You can change document.body to window:
window.onload = function()
{
window.onscroll = function()
{
console.log("Calling this function");
}
}
I noticed that in chrome onscroll event is working when body element has onscroll attribute, but in IE it's working when html element has onscroll attribute, so it's the best to assign onscroll event listener to window object.
PS. if you want to check how many pixels you scrolled - use window.pageYOffset instead of document.body.scrollTop (the same situation with chrome and IE as described above).
You don't want the () when you're assigning callFn as the onscroll handler.
You don't want to execute the function, you want to assign a reference to it.
In addition, onscroll for an entire document seems to work better cross-browser on the window object, rather than document or document.body.
window.onscroll = Test.callFn;
I had the same issue and it was because I had overflow-x: hidden assigned to the body. Removing this fixed the problem.
window.onscroll does not work at times when you style an element using theheight property of css.
try using min-height or max-height instead.
One of the possibility is there are two window.onscroll statements on your page that each statement calling different JS method. Check the included files and all the methods that are in the page loading.
This might also happen when the height of html and body tags is set to 100% and the scroll event does not fire for window nor document. To check which element is scrolled I slightly modified Aaron Mason's snippet which wasn't working for me either:
document.querySelectorAll('*').forEach(function(elem) {
elem.addEventListener('scroll', function() {
console.log(this);
});
});
In Chrome, it works if you attach the event handler to the document.onscroll event:
document.onscroll = function() { console.log('Works in Chrome!'); };