Reputation: 22323
When I load a page with a hash tag in the URL, the page loads and then jumps to the anchor tag. Is there any way to prevent this "jump", either by loading the page directly to the anchor tag or at least making the scrolling smooth?
I see this problem in Chrome and Firefox, but not IE.
Upvotes: 3
Views: 2085
Reputation: 557
I see the problem still preserves with Firefox in XSL and XML files, but already not with HTML. I solve it with this work-about:
<script>
var pattern = new RegExp('\#(.*)');
var id = pattern.exec(window.location)[0].replace('#','');
var id2 = pattern.exec(window.location)[0];
function gotoanchor() {
if ( (typeof id2) != "undefined") {
document.location=id2;
alert("We are at the anchor "+id);
}
}
</script>
</head> <!-- in the head section -->
<body onload="gotoanchor();">
Upvotes: 0
Reputation: 852
If you're still experiencing the jumping issue, you could something with jQuery:
//Use a RegEx pattern to search for an id, if present
var pattern = new RegExp('\#(.*)');
var id = pattern.exec(window.location)[0].replace('#','');
//Prevent the browser's default behavior of jumping to the id
document.location = '#';
//When the page finishes loading, smoothly scroll to the specified content
$(document).ready(function() {
if(id != "") {
$('html,body').animate({
scrollTop: $('#' + id).offset().top,
}, 650);
}
});
Note that this will only work once per page load.
Upvotes: 2