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.
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.
3
Answers
scrollTop
will initially get set to 0, then every time you log it, it’s going to use that value.If you want a new value for
scrollTop
, it needs to be recalculated. Put the calculation inside of your function bound towindow.onscroll
.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:
Plain JS:
Your
scrollTop
variable is initialized but it is not updated inside theonscroll
function, that’s why it remains unchanged. Explanation: youronscroll
function is called each time you move your cursor, and its state (positions:e.pageY
) is stored in the variablee
of youronscroll
function.Here is a way to get the cursor/pointer position onScroll using jQuery: