Reputation: 247
This is driving me crazy. If you have navigation with anchors on the same page, when popstate is invoked, the browser will naturally take you back/forward to the location of that link in your history.
It would be assumed that you could disable the hash jump from happening as you would in a click event via e.preventDefault(); - but that has not been the case thus far.
In most modern browsers, I have been able to hack an override by storing something like $(window).scrollTop(); in a variable and calling it back inside the popstate: $window.scrollTop(somevar);
However in Safari, this workaround causes a quick blip or flash of the original anchor location before relocation to the specified scrollTop - which makes it a non solution
After trying various ideas, it seems that the only way to achieve what I need is to find a way to make Safari treat those anchors the way Chrome or FF does, or somehow disable them entirely on a popstate idea.
Here's sample of the previously mentioned override (works in chrome, FF etc)
var scrollY;
$(window).on('scroll', function(e) {
scrollY = $window.scrollTop();
});
$(window).on('popstate', function(e) {
// some other page location, not the history #hash
$(window).scrollTop(scrollY);
});
Upvotes: 1
Views: 1532
Reputation: 247
Solved
From what I could tell there was no obvious way to accomplish this, so I spent my time on a work around method. Rather than attempting to stop the hash, I was able to achieve the desired effect by temporarily giving the container position fixed + current scroll position then removing the adjustment after the page transition function was complete.
var scrollY;
$(window).on('scroll', function(e) {
scrollY = $window.scrollTop();
});
$(window).on('popstate', function(e) {
$(window).scrollTop(scrollY);
$('.container').css({
'position': 'fixed',
'top': '-'scrollY+'px'
});
yourFunction(); // contains animation sequence / css removal
});
Upvotes: 1