-1

Consider the following inline code below:

<h1 id="top">Top Of Page</h1>
...
<a class='reload' onClick='window.location.reload();'>Reload</a>

How would one implement this in a fashion where when the window reloads, it goes to the top of the page of hits the anchor? I tried just doing:

reload to top of page

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

and:

Reload browser does not reset page to top

$(document).ready(function(){
    $(this).scrollTop(0);
});

Directly in the related template but it wouldn't load to top? Besides jQuery not being included Why would that be?

Is there a way to do this inline to keep consistent? so something like (which I tried):

<a class='reload' onClick='window.location.reload().scrollTop(0);'>Reload</a>

Which doesn't go to the top of the page, either.

I then thought to do the href of the id I can anchor to:

anchor jumping by using javascript (slightly tweaked to my situation)

<script type="text/javascript">
function goToTop(){
    var url = location.href;               
    location.href = url + "#top";             
}
</script>

<a class='reload' onClick='goToTop()'>Reload</a>

In this approach, it just adds "#top" to the URL and nothing else.

I was under the impression what if you change location.href it redirects to the new URL. It says here that "The href property sets or returns the entire URL of the current page." Why won't it set it in the above function?

This seems pretty simple so I'm not understanding what I'm missing?

kawnah
  • 2,503
  • 4
  • 31
  • 70

2 Answers2

1

You just need to add window.location.reload(true) after the line where you set [window.]location.href to your anchor.

Related

MT_
  • 96
  • 1
  • 1
  • 10
  • Ok, but how do I prevent it from doing it multiple times. Clicking three times goes `www.example.com#top#top#top` – kawnah Jul 25 '18 at 18:13
  • 2
    @kawnah `window.location.hash = 'whatever'` will not duplicate the hash – Taplar Jul 25 '18 at 18:18
1

Posting answer by @epascarello embedded in comments, above, as it worked for me and is the simplest answer I've seen.

If you don't need/want any animated reload actions, simply use two different events - first to move the current page/scroll location to the top [window.scrollTo(0,0);] and then reload the page, either from the cache [window.location.reload();] or from the server if you've updated any of the needed data [window.location.reload(true);]. So,

// Moving page to top on forced reload in javascript
window.scrollTo(0,0); 
window.location.reload();    //or window.location.reload(true) to use new/updated data from the server

Hope this helps others. Thanks, again, @epascarello!

S. Carter
  • 11
  • 2