Simple slideTo using jQuery
Ever find yourself wanting to slide down to a particular div when an anchor tag is clicked?
Here's a quick little snippet to use on all of your anchors that are hooked to a Div ID.
$(function($){
$('a').on('click', function(e){
var $anchor = $(this).attr("href");
var $hrefStart = $anchor.substr(0, 1);
if ( $hrefStart == "#" ) {
$('html,body').animate({
scrollTop: $($anchor).offset().top
}, 1500, 'easeInOutExpo');
e.preventDefault();
} else {
window.location.href = $anchor;
}
});
})(jQuery);
Written by Jake Chapman
Related protips
5 Responses
Just curious...is this for any version of jQuery or specific to a particular version? Can you post what version you used for this?
@skaggej Hey, this shouldn't be version specific. The only thing to watch out for is the 'Easing' parameter which you have to have jQuery UI running as well. Hope this helps
Cool, I just always like to know about version specificity as I come across things. Since this one isn't limited to a specific version, we're in good shape. Thanks for the response.
what about the $("a[href*=#]") selector?
You can detect anchor links using the selector, meaning you don't have to handle the alternate course (normal link) within the handler function.
In addition, delegating the 'a[href^=#]' means that any anchor links that are loaded later will also slide.
$('body').on('click', 'a[href^=#]', function (evt) {
var $anchor = $(this).attr("href");
$('html,body').animate({
scrollTop: $($anchor).offset().top
}, 1500, 'easeInOutExpo');
evt.preventDefault();
});