Smooth Scrolling – With Bootstrap

Posted on: January 16th, 2017 by alemieux

Sending users to in-page targets with an ID can be jarring. They might lose context of the page when they move further down and they lose site of what came previously. A smooth scrolling animation can solve this issue and looks great!

This Pen has a great example: http://codepen.io/chriscoyier/pen/dpBMVP However, the page I was building also included Bootstrap Panels (Accordion). Since the target is any ID on the page, that will include the targets in the Panels, so it broke the functionality. I did some brief searching and found a StackOverflow response that tweaks the code to refine the targeting so as not to affect Bootstrap Carousels, or Panels. Here’s the full code:

$(document).ready(function() {
  $('a[href*="#"]:not([href="#"]):not([data-toggle])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);
            return false;
        }
    }
  });
});

Now I have the functionality I want for scrolling to targets and the Panels still work.

Tweet this! | Bookmark at Delicious

Tags: , , ,

Comments are closed.