I am trying to use jQuery to scroll the page automatically back to the top when the page is loaded. Here is my code:
<script type="text/javascript">
$(document).ready(function () {
$(window).scrollTop(0);
return false;
});
</script>
However, the code does not work.
I have also tried to replace $(window)
to $('html, body')
,
sadly it still does not work.
So could anyone advice on this? Thanks a lot!
Last Updated : 14 May, 2019 To auto scroll a page from top to bottom we can use scrollTop () and height () method in jquery. In this method pass the document’s height in scrollTop method to scroll. Example-1: Scroll without animation.
For browsers that don't support this, you could create a fallback to using window.onbeforeunload, for example, in the following way: Before the page unloads, we can change the scroll position to the top of the page. This would change the browser's last scroll position, and when the page refreshes it would start at the top of the page.
Definition and Usage. The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0. When used to return the position: This method returns the vertical position of the scrollbar for the FIRST matched element. When used to set the position:
The scrollTop () method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0. This method returns the vertical position of the scrollbar for the FIRST matched element. This method sets the vertical position of the scrollbar for ALL matched elements.
Try this
<script type="text/javascript">
$(document).ready(function () {
window.scrollTo(0,0);
});
</script>
The parameters 0,0 are the x and y coördinates.
I hope it helps.
The above solutions didn't work for me in Chrome. This is what I had the most success with:
$(window).on('beforeunload', function() {
$('body').fadeOut(225);
});
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