Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why ScrollTop is always 0?

I want to know what is scrollTop and using jQuery. But, it’s always showing 0.

here is my jQuery code:

var scrollTop = $(window).scrollTop()

//onscroll
window.onscroll = function (e) {
    console.log(scrollTop);
}

If need, I can also add HTML and CSS codes.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I try to use JavaScript:

var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;

//onscroll
window.onscroll = function (e) {
    console.log(scrollTop);
}

But, same.

If answer isn’t writed in jQuery it’s better.

>Solution :

The value of scrollTop is not being updated dynamically in the onscroll event handler. Instead, it is only assigned once when the script is initially run.
Maybe this?

Using jQuery:

// onscroll
$(window).scroll(function () {
  var scrollTop = $(window).scrollTop();
  console.log(scrollTop);
});

Plain JS:

// onscroll
window.onscroll = function (e) {
  var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  console.log(scrollTop);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading