Last Updated: September 09, 2019
·
9.678K
· imjakechapman

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);

5 Responses
Add your response

Just curious...is this for any version of jQuery or specific to a particular version? Can you post what version you used for this?

over 1 year ago ·

@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

over 1 year ago ·

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.

over 1 year ago ·

what about the $("a[href*=#]") selector?

over 1 year ago ·

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();
});
over 1 year ago ·