Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go to the anchor link after window.location.reload

I'm trying to update hash and then reload page.

$('a[name="' + fragment + '"]').remove(); //don't jump before window reloads
window.location.hash = fragment;
window.location.reload(true);

After reload window doesn't jump to anchor tag. How can I fix it?

like image 825
fedor.belov Avatar asked Dec 19 '12 11:12

fedor.belov


2 Answers

This is fairly trivial to achieve in jQuery if you are reloading the page. Just check the window.location.hash property when loading the page.

$(document).ready( function( ) {
    if( window.location.hash ) { // just in case there is no hash
        $(document.body).animate({
            'scrollTop':   $( window.location.hash ).offset().top
        }, 2000);
    }
});

The only caveat is that your hash matches the id of the element you are scrolling to.

Demo here

like image 76
Bruno Avatar answered Nov 13 '22 10:11

Bruno


MOZILLA DEVELOPER NETWORK suggest using replace:

function reloadPageWithHash() {
  var initialPage = window.location.pathname;
  window.location.replace('http://example.com/#' + initialPage);
} 
like image 43
Eugene Avatar answered Nov 13 '22 09:11

Eugene