Skip to content

Instantly share code, notes, and snippets.

@bcole808
Last active August 29, 2015 13:57
Show Gist options
  • Save bcole808/9500995 to your computer and use it in GitHub Desktop.
Save bcole808/9500995 to your computer and use it in GitHub Desktop.
Smooth scrolling to anchors using jQuery
$(document).ready(function() {
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
/***************
* CONFIGURATION
****************/
// How fast should the transiion be?
var transition_speed = 400; // milliseconds
// How far before we speed up the scroll FX?
var max_scroll_pixels = 2800; // pixels
/***************
* END CONFIGURATION
****************/
var
target = this.hash,
target_offset = $(target).offset().top,
window_offset = $(document).scrollTop(),
delta = target_offset - window_offset;
if (Math.abs(delta) > max_scroll_pixels) {
transition_speed = 100;
}
$('html, body').stop().animate({
'scrollTop': target_offset
}, transition_speed, 'swing', function () {
window.location.hash = target;
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment