Hei
Hei

Reputation: 513

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!

Upvotes: 6

Views: 40998

Answers (4)

Udochukwu Enwerem
Udochukwu Enwerem

Reputation: 2823

This is jQuery safe:

< script type="text/javascript">
  $(window).scrollTop(0); 
</script>

Upvotes: 0

taylorpoe
taylorpoe

Reputation: 11

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);
});

Upvotes: 1

Attilio
Attilio

Reputation: 31

Is easier and more reliable if you use this solution:

<script type="text/javascript">
   $('html,body').animate({scrollTop:0},800);
</script>

In fact some browsers will respond to 'html' and some to 'body'.

PS. "800" is the duration of the animation.

Upvotes: 0

fonZ
fonZ

Reputation: 2479

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.

Upvotes: 10

Related Questions