Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto scroll top when page loaded using jQuery

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!

like image 226
Hei Avatar asked Aug 21 '12 01:08

Hei


People also ask

How to auto scroll a page from top to bottom in jQuery?

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.

How can I change the scroll position before the page unloads?

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.

What is the use of scrolltop in HTML?

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:

How do I set the vertical scrollbar position of the selected element?

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.


2 Answers

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.

like image 158
fonZ Avatar answered Nov 15 '22 01:11

fonZ


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);
});
like image 28
taylorpoe Avatar answered Nov 14 '22 23:11

taylorpoe