Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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

like image 395
anoonimo Avatar asked Sep 27 '13 18:09

anoonimo


People also ask

What is scrollTop in Javascript?

scrollTop property gets or sets the number of pixels that an element's content is scrolled vertically. An element's scrollTop value is a measurement of the distance from the element's top to its topmost visible content. When an element's content does not generate a vertical scrollbar, then its scrollTop value is 0 .

How do I make the page scroll to the top on refresh?

onbeforeunload property to a function that calls window. scrollTo with 0 and 0 to scroll to the top. Now when we refresh the page, we scroll to the top of the page.

How do I stop a Web page from scrolling to the top when a link is clicked that triggers javascript?

Call the . preventDefault() method of the event object passed to your handler.

What does scrollTop return?

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.


1 Answers

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

like image 133
sebastian Avatar answered Oct 19 '22 14:10

sebastian