Skip to content

Instantly share code, notes, and snippets.

@bUxEE
Last active September 5, 2018 20:42
Show Gist options
  • Save bUxEE/fc283c348d139785e8c68cbc379e61b8 to your computer and use it in GitHub Desktop.
Save bUxEE/fc283c348d139785e8c68cbc379e61b8 to your computer and use it in GitHub Desktop.
Smooth scroll to ID from link or url
////////////////////////////////////////////////////////////////////////////////
// SMOOTH SCROLL TO ID
////////////////////////////////////////////////////////////////////////////////
var scrollIt = function(divID, speed) {
if($(divID).length) {
var elemTop = $(divID).offset().top;
$('html, body').animate({
scrollTop: elemTop
}, 800).promise().then(function() {
$(document).trigger('jquery_scrolling', {newPos: elemTop});
});
} else {
console.log('trying to scroll to missing element ' + divID);
}
}
$(window).load(function (e) {
if (window.location.hash) {
var id = window.location.hash;
scrollIt(id);
}
});
$(document).on('click', 'a[data-scroll]', function (event) {
var target = $(this).attr('data-scroll');
if (target != "") {
event.preventDefault();
scrollIt( "#" + target);
}
});
$(document).on('click', 'a[href^="#"]', function (event) {
var target = $(this).attr('href');
if (target.length > 1) {
event.preventDefault();
scrollIt(target);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment