Skip to content

Instantly share code, notes, and snippets.

@t3easy
Created February 15, 2015 20:01
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 t3easy/f004d0ecb61743f78c50 to your computer and use it in GitHub Desktop.
Save t3easy/f004d0ecb61743f78c50 to your computer and use it in GitHub Desktop.
// Start scroll
function scrollToAnchor(hash, duration) {
var target = $(hash), header, scrollTop = 0;
target = target.length > 0 ? target : $('[name=' + hash.slice(1) +']');
if (target.length > 0) {
header = $('#header');
scrollTop = target.offset().top;
if (target.attr('id') !== 'top' && header.length > 0 && header.css('position') === 'fixed'){
scrollTop = scrollTop - header.height();
}
$('html,body').animate({
scrollTop: scrollTop
}, duration, function () {
window.location.hash = hash;
});
}
}
if (typeof String.prototype.startsWith !== 'function') {
String.prototype.startsWith = function (str){
return this.slice(0, str.length) === str;
};
}
// Open page with anchor
if(window.location.hash && window.location.hash.startsWith('#c')) {
scrollToAnchor(window.location.hash, 0);
}
// Scroll to anchor on same page
$('a[href*=#]:not([href=#])').click(function(e) {
if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') && location.hostname === this.hostname) {
scrollToAnchor(this.hash, defaultDuration);
e.preventDefault();
return false;
}
});
// End scroll
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment