Quick and Simple “Scroll to Div” Method; jQuery

Sometimes, you might need to scroll a user to a div when they click a particular element. In fact, these days, it seems pretty commonplace to do so, especially with the new “long” homepages. In the past, people might jump you to an anchor point using #, but this is clunky as it brings the user immediately to the desired location, diminishing the user experience.

Instead, we want to scroll them smoothly. So, we will use a small bit of jQuery to do so.

Making use of jQuery’s .animate() function, we can achieve this very easily:


jQuery(document).ready(function($){ //here we begin the function
     $('#element-to-click').click(function(){ // here we set the click function on the trigger element
          $('html,body').animate({ // here we use the .animate() function to scroll smoothly
                scrollTop: $('#element-to-scroll-to').offset().top // here we use the offset of the element to scroll to
          });
     });
});

There we have it, it’s just that simple.

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>