Skip to content

Instantly share code, notes, and snippets.

@peacefulseeker
Last active November 27, 2017 16:09
Show Gist options
  • Save peacefulseeker/44bad8773b7d3d09012b93164a11699b to your computer and use it in GitHub Desktop.
Save peacefulseeker/44bad8773b7d3d09012b93164a11699b to your computer and use it in GitHub Desktop.
jQuery - Smooth Scrolling to Element
(function($) {
$("a[href^='#']")
.not('[href="#"]')
.not('[href="#0"]')
.on('click', function ( event ) {
event.preventDefault();
var $scrollTarget = $( $(this).attr('href') );
$scrollTarget = $scrollTarget.length ? $scrollTarget : $('[name="' + $(this).attr('href').slice(1) + '"]');
/* If not found stop execution */
if ( !$scrollTarget.length ) return;
scrollToTarget($scrollTarget, 0, -140);
});
if ( location.hash.length && $(location.hash).length ) {
scrollToTarget( $(location.hash), 1000, 0 );
}
function scrollToTarget(scrollTarget, delay, offset) {
$('html,body').not(":animated").delay(delay).animate({
scrollTop: scrollTarget.offset().top + offset
}, 400);
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment