Skip to content

Instantly share code, notes, and snippets.

@carasmo
Created February 22, 2016 18:58
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 carasmo/eb4606d5369ae2e3ba5e to your computer and use it in GitHub Desktop.
Save carasmo/eb4606d5369ae2e3ba5e to your computer and use it in GitHub Desktop.
Smooth scroll to anchor on load and click. Credit: http://stackoverflow.com/a/20320919/1004312
(function(document, $, undefined) {
'use strict';
$(document).ready(function() {
//* -------- smooth scroll to anchor links on click and load ----------------------------------------------------
//Credits: http://stackoverflow.com/a/20320919/1004312
//http://stackoverflow.com/users/393459/shouvik
//smooth scroll to anchor
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 80 //offsets for fixed header
}, 1500);
return false;
}
}
});
//Executed on page load with URL containing an anchor tag.
if ($(location.href.split("#")[1])) {
var target = $('#' + location.href.split("#")[1]);
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 80 //offset height of header here too.
}, 1500);
return false;
}
}
}); //end ready
})(document, jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment