anoonimo
anoonimo

Reputation: 367

ScrollTop on page reload doesn't work (possible script conflict)

I'm working on this page http://dindita.com/preview.html

I added this to make it scroll to the top when someone refreshes the page but doesn't seem to work, I wonder if it's a conflict with the other scrolling scripts I'm using.

<script type="text/javascript">
    $(document).ready(function(){
    $(this).scrollTop(0);
});
</script>

Any clue?

P.s.: work in progress: messy scripts

Upvotes: 11

Views: 29565

Answers (5)

harshes53
harshes53

Reputation: 429

I had that Eureka moment when I tried this and it worked:

<script> location.hash = (location.hash) ? location.hash : " "; </script>

In <head> of your html. Not sure about single page app! But sure works like charm in regular pages.

Upvotes: 3

boj4n
boj4n

Reputation: 31

Calling scrollTo and again scrollTo with timer in 10 ms and changing value for 1 px did the job. Working on chrome and safari for each forced refresh.

w = 200;

scrollTo(w - 1, 0);
window.setTimeout (function (){scrollTo(w, 0);}, 10);

Upvotes: 0

ouija
ouija

Reputation: 306

This is what I came up with to scroll to top but only when document isn't already at the top, and delayed just enough not to cause an issue with it firing properly:

$(window).load(function() {
    setTimeout(function() {
        if ($(document).scrollTop() !== 0) $("html, body").animate({ scrollTop: 0 }, 'fast');
}, 300);
});

Upvotes: 0

sebastian
sebastian

Reputation: 17348

Try this:

$(document).ready(function() {
  $("html,body").animate({scrollTop: 0}, 100); //100ms for example
});

Or this:

window.onload = function() {
 setTimeout (function () {
  scrollTo(0,0);
 }, 100); //100ms for example
}

Or this:

$(window).on('beforeunload', function() {
    $(window).scrollTop(0); 
});

Browsers tend to jump back to their last scroll position on a reload, which makes sense in many cases. It seems that this automatic jump gets triggered right after the onload event (but we don't know the exact moment when this happens), so it makes sense to either use some delay, or have the browser scroll to the top before the page reloads ;)

Upvotes: 35

Jakub Kotrs
Jakub Kotrs

Reputation: 6244

Browsers (at least Chrome) change the scroll position after the page is loaded, not when the DOM is ready.

$(window).load(function(){
    $('html, body').scrollTop(0);
});

If that doesn't work (script is still executed before the browser changes scroll position), you can set a timeout:

$(window).load(function(){
    setTimeout(function() {
        $('html, body').scrollTop(0);
    }, 10);
});

Upvotes: 6

Related Questions