Running the following in Chrome always returns 0:
$(window).on('load', function(){
console.log($(window).scrollTop());
});
Running that same command via the console:
$(window).scrollTop()
Does return the correct number. (i.e.: 843)
There are a lot of questions about this issue here on StackOverflow but none of them have given me a correct working answer or alternative. I'm at a loss...
The scrollTop()
returns the current vertical position of the scroll bar. Typically on page load, the scroll bar is at position 0
. If the console prints out something else, then you or the browser must have scrolled down before the function was called.
If you are using named anchors or refreshing the page from a scrolled position, you can bind a handler to the scroll event that only triggers once - on page load:
$(window).on('scroll', function() {
console.log( $(this).scrollTop() );
});
There are many ways to get the current scroll position In page
First get pageYOffSet
let verticalScrollOffset = window.pageYOffset;
then Set
window.scrollTo(0,verticalScrollOffset);
If you need both Side position and set then
let scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
let scrollTop = window.pageYOffset || document.documentElement.scrollTop;
window.scrollTo(scrollLeft,scrollTop);
Using ViewportScroller click here to know more
this.viewportScroller.scrollToPosition(this.viewportScroller.getScrollPosition());
//does not helps in my case
Ideal Solution works for me, I just save verticalScrollOffset(YaxisSrollPosition) before loading the page or refresh in any constant variable or local storage.Then After Refresh or load the page Use that position
let verticalScrollOffset = window.pageYOffset || document.documentElement.scrollTop;
$("html, body").animate({ scrollTop: verticalScrollOffset }, "slow");//slow Or fast option
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With