I have a link to a page that dynamically adds content to a div. What I want to achieve is prevent default browser scrolling to the anchor when the page loads. After searching and trying various solutions found on the web I ended up to the following copied from this stack overflow question :
page1.html
<a href="url/to/page2/#anchor_name">link to page 2</a>
page2.html
<div id="load-data-received-from-ajax"></div>
<script>
var hash = window.location.hash
var scrollToAnchor = function(hash) {
// If got a hash
if (hash) {
// Scroll to the top (prevention for Chrome)
window.scrollTo(0, 0);
// Anchor element
var term = $(hash);
// If element with hash id is defined
if (term) {
// Get top offset, including header height
var scrollto = term.offset().top - 55;
// Capture id value
var id = term.attr('id');
// Capture name value
var name = term.attr('name');
// Remove attributes for FF scroll prevention
term.removeAttr('id').removeAttr('name');
// Scroll to element
$('html, body, document').animate({scrollTop:scrollto}, 0);
// Returning id and name after .5sec for the next scroll
setTimeout(function() {
term.attr('id', id).attr('name', name);
}, 500);
}
}
};
$( document ).ready(function(){
$.ajax({
url: '',
type: 'get',
success: function(data){
$('#data').html(data);
scrollToAnchor(hash);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#data').html('There was an error!);
}
});
});
</script>
This works for Chrome but not for Firefox. On FF the window scrolls to the element defined in hash but when the id attribute is again added to the element, FF scrolls to that point (which does not include the header height). Any ideas why this doesn't work?
Just add the scroll-
prefix to your hash:
<a href="url/to/page2/#scroll-anchor-name">link to page 2</a>
<div id="anchor-name">...</div>
and at run-time just check and remove it:
var hashtpl = "#scroll-";
if (hash && hash.match(RegExp('^' + hashtpl, 'gi')) !== null) {
hash = "#" + hash.substring(hashtpl.length());
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.