Skip to content

Instantly share code, notes, and snippets.

@SafeerH
Last active August 29, 2015 14:05
Show Gist options
  • Save SafeerH/455d7d698eb7da8298cd to your computer and use it in GitHub Desktop.
Save SafeerH/455d7d698eb7da8298cd to your computer and use it in GitHub Desktop.
Smooth scroll to an element with jQuery
/// Usage: (HTML)
///
/// <a data-smooth-scroll href="#section1">Section 1</a>
///
/// <div id="section1">This is section 1</div>
$(document).ready(function() {
$('a[href^="#"][data-smooth-scroll]').on('click', function(event) {
var href = $(this).attr('href');
var target = $(href);
if (href.length && target.length > 0) {
event.preventDefault();
var navHeight = $('.navbar.navbar-fixed-top').height();
$('html, body').animate({
scrollTop: target.offset().top - navHeight
}, 500);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment