Skip to content

Instantly share code, notes, and snippets.

@yuval-a
Last active August 29, 2015 14:19
Show Gist options
  • Save yuval-a/3cbaed4c99a8c10d57ce to your computer and use it in GitHub Desktop.
Save yuval-a/3cbaed4c99a8c10d57ce to your computer and use it in GitHub Desktop.
JQuery - Smooth scroll to any anchor
$window.load(function() {
var scrollOffset = ; // Do some padding calculations etc. - this will be substracted from the target item top position
// Assign to any links/buttons with '#something' in their href.
$('#nav a').on('click',function(e) {
var $href = $(this).attr('href'),
hi = $href.indexOf('#');
// If no hash part return;
if (hi==-1) return true;
e.preventDefault();
// The double decodeURI is to support non-english
var targetid = decodeURI(decodeURI($href.substring(hi)));
targetTop = $(targetid).offset().top - scrollOffset;
$("html, body").animate({scrollTop: targetTop}, 1000);
//Change URL on browser window
if (window.history)
window.history.pushState(null, "", targetid);
return false;
});
// If URL contains anchor - auto scroll to it:
var $hash = window.location.hash;
if ($hash) {
$hash = $hash.replace(/\s/g,'-');
var targetid = $hash;
targetTop = $(targetid).offset().top - scrollOffset;
$("html, body").animate({scrollTop: targetTop}, 1000);
//Change URL on browser window
if (window.history)
window.history.pushState(null, "", targetid);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment