Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS Bootstrap Basics Using Bootstrap Components Using ScrollSpy to Highlight Nav Links

Rama Olson
Rama Olson
11,670 Points

Adding Smooth Anchor Scrolling

For anyone that's looking to add smooth anchor scrolling for nicer appearance:

JS -

$('a[href*=\\#]:not([href=\\#])').click(function() { //need to escape pound sign in script or you'll get an error

        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
                || location.hostname == this.hostname)
        {

            var target = $(this.hash),
            headerHeight = $("header").height() + 5; // Get fixed header height

            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

            if (target.length)
            {
                $('html,body').animate({
                    scrollTop: target.offset().top - headerHeight
                }, 500);
                return false;
            }
        }
    });

adjust $("header") to whatever the tag, class, or id is for your header. also add data-offset to your scrollspy or active links won't fire correctly

source credit: https://gist.github.com/HoundstoothSTL/5510082

1 Answer

Ash Scott
Ash Scott
435 Points

Edit: Mis-read smooth scroll as actual smooth scroll (on mouse). Anchor scrolling would be more fitting (As per the gist :P )

Rama Olson
Rama Olson
11,670 Points

Thanks, I just updated it. We always call it smooth scroll at my work but I can see how that can be confusing.