Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery Scroll To with history.pushState support for using the back button and the location bar: http://stackoverflow.com/a/16732655
$(document).on('click', 'a[href*=#]', function(event){
event.preventDefault();
var targetId = this.hash;
var theTarget = $(targetId);
var customOffset = 0;
switch( targetId ){
case '#target1':
case '#target2':
customOffset = -80;
break;
default:
customOffset = -30;
}
if (theTarget.length) {
var targetOffset = (theTarget.offset().top) + customOffset;
var stateData = {
path: window.location.href,
scrollTop: targetOffset
};
window.history.replaceState(stateData, '', targetId);
window.history.pushState(stateData, '', targetId);
$('html,body').animate({scrollTop: targetOffset}, 1000);
return false;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.