Skip to content

Instantly share code, notes, and snippets.

@gfarrell
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gfarrell/3a7ae0211be5351c5323 to your computer and use it in GitHub Desktop.
Save gfarrell/3a7ae0211be5351c5323 to your computer and use it in GitHub Desktop.
$(window).on('load', function() {
var fragment = window.location.hash;
if(fragment != "") {
$('body').animate({
scrollTop: $(fragment).offset().top
});
}
});
$(function() {
var selector = 'a';
// cycle through all links
$(selector).each(function(i, el) {
var $el = $(el);
var parts, href, $target;
// we only want to deal with those elements that have a hash fragment
href = $el.attr('href');
if(href.indexOf('#') != -1) {
// we also only need to deal with those links that link to the current page
parts = href.split('#');
if(window.location.pathname == parts[0]) {
$target = $(parts[1]);
// now we have both a common path and a hash fragment
// attach a click handler
$el.on('click', function(e) {
e.preventDefault();
$('body').animate({
scrollTop: $target.offset().top
});
});
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment