Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Rama Olson
Rama Olson
11,658 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
423 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,658 Points

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