Reputation: 23323
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?
Upvotes: 7
Views: 7533
Reputation: 2193
@Tim S. my intention is absolutely not to steal your thunder but your very low key comment above is in my opinion the optimal solution to this question as it is simple, clean and tests successfully across a variety of browsers. I am therefore creating an answer of it on your behalf:
window.location.href = url#anchor
(where url can be the current page - or a different one as desired)
Upvotes: 0
Reputation: 5822
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
Upvotes: 2
Reputation: 3375
MOZILLA DEVELOPER NETWORK suggest using replace
:
function reloadPageWithHash() {
var initialPage = window.location.pathname;
window.location.replace('http://example.com/#' + initialPage);
}
Upvotes: 1