Smooth Scrolling in jQuery – Quick Tip

javascriptQuickTips

From start to finish, this quick tip with Andrew Chalkley will take you through an example using jQuery’s Smooth Scrolling on a FAQ page.

Andrew Chalkley

I'm an alien, I'm a legal alien, I'm an Englishman in Portland. All of my professional life I've worked with computers online. I'm a polyglot programmer and like using the right tools for the job. In my spare time I enjoy spending time with my young family and when I get chance, sticking opponents in Halo 4. You can find me in most places @chalkers.

Comments

7 comments on “Smooth Scrolling in jQuery – Quick Tip

  1. Nice Quicktip. Would be nice to add a scrolling “link to top” for those who have longer FAQs that would bring the user back to the top..

  2. Nice tip! This works in Google Chrome / Safari / Firefox, but fail in IE. So, to work crossbrowser, just do it:

    $( ‘html, body’ ).animate({ $( faqId ).offset().top }, ‘slow’);

    And for best practices, use “event.preventDefault()” instead of “return false”;

    The complete code:

    $( ‘#faq a’ ).click( function( e ) {
    e.preventDefault();
    var faqId = $( this ).attr( ‘href’ );
    $( ‘html, body’ ).animate({ scrollTop : $( faqId ).offset().top }, ‘slow’);
    });

  3. how abt scrolling it horizontally… ?i tried below code.. but dint wrk :(
    $( ‘html, body’ ).animate({ scrollTop : $( faqId ).offset().right}, ‘slow’);

    • @Vipin jquery offset() returns an object with the properties of left and top.
      In your example, you could try:

      $('html, body').animate({scrollTop:$(faqId).offset().left}, 'slow');

      Hope it helps!

      For more on jquery offset: http://api.jquery.com/offset