Skip to content

Instantly share code, notes, and snippets.

@neutraltone
Last active July 6, 2016 15:24
Show Gist options
  • Select an option

  • Save neutraltone/92326ecb87dbd59fa9afeab7e8d884d5 to your computer and use it in GitHub Desktop.

Select an option

Save neutraltone/92326ecb87dbd59fa9afeab7e8d884d5 to your computer and use it in GitHub Desktop.
/**
* In page anchor header offset
* ----------------------------
* Check a href for an anchor. If exists, and in document, scroll to it.
* If href argument ommited, assumes context (this) is HTML Element,
* which will be the case when invoked by jQuery after an event
*/
function scroll_if_anchor(href) {
href = typeof(href) == "string" ? href : $(this).attr("href");
// You could easily calculate this dynamically if you prefer
var fromTop = $('.header').height() + 24;
// If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo)
// Legacy jQuery and IE7 may have issues: http://stackoverflow.com/q/1593174
if(href.indexOf("#") == 0) {
var $target = $(href);
// Older browser without pushState might flicker here, as they momentarily
// jump to the wrong position (IE < 10)
if($target.length) {
$('html, body').animate({ scrollTop: $target.offset().top - fromTop });
if(history && "pushState" in history) {
history.pushState({}, document.title, window.location.pathname + href);
return false;
}
}
}
}
// Intercept all anchor clicks
$("body").on("click", "a", scroll_if_anchor);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment