6

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!

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Hei
  • 513
  • 3
  • 13
  • 29

4 Answers4

10

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.

fonZ
  • 2,428
  • 4
  • 21
  • 40
  • Thanks for the suggestion, however it does not too. Is it because I have wrapped the page inside an iframe? – Hei Aug 21 '12 at 02:23
  • 1
    I'm not sure, this might help http://stackoverflow.com/questions/1192228/scrolling-an-iframe-with-javascript – fonZ Aug 21 '12 at 16:23
1

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);
});
taylorpoe
  • 11
  • 3
0

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.

Attilio
  • 31
  • 5
0

This is jQuery safe:

< script type="text/javascript">
  $(window).scrollTop(0); 
</script>
Udo E.
  • 2,665
  • 2
  • 21
  • 33