Skip to content

Instantly share code, notes, and snippets.

@clayb
Last active October 23, 2018 14:17
Show Gist options
  • Select an option

  • Save clayb/9ec5f8bc53ee0a163b7b to your computer and use it in GitHub Desktop.

Select an option

Save clayb/9ec5f8bc53ee0a163b7b to your computer and use it in GitHub Desktop.
Smooth Scroll Anchor jQuery
// Better way
function scrollToTarget(target, shift = 0, timing = 500) {
$('html, body').animate({
scrollTop: $(target).offset().top + shift
}, timing);
}
// Same as above but with IE friendly default parameters
function scrollToTarget(target, shift, timing) {
if (typeof shift == 'undefined') {shift = 0}
if (typeof timing == 'undefined') {timing = 500}
$('html, body').animate({
scrollTop: $(target).offset().top + shift
}, timing, 'easeOutCirc');
}
// Or attach to window object for global access
window.scrollToTarget = function(target, shift = 0, timing = 500) {
$('html, body').animate({
scrollTop: $(target).offset().top + shift
}, timing);
}
// Older way
$('.smooth-scroll').click(function(e){
e.preventDefault();
var target = $(this).attr("href");
$('html, body').animate({ scrollTop: $(target).offset().top - 50 }, 500);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment