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

JavaScript

Gina Scalpone
Gina Scalpone
21,330 Points

When nav is clicked, follow link then smooth scroll to content?

I know how to add a smooth scroll with jQuery to another part of the same page, but is it possible to add an scroll when one clicks on one of my nav links? I have a large header that I love, but when I click on my about page, I would like to just go straight to my content.

1 Answer

Gina Scalpone
Gina Scalpone
21,330 Points

I found an answer after a bunch of googling, in case anyone has a similar problem! Make sure to add the id of the div you're trying to scroll to in the navigation list item of the page it's on. For instance:

<li><a href="page.html#nav">Page</a></li>

That will take you to the navigation on the page.html. Add this to all the pages BUT page.html. On page.html, you'll add a class to the anchor element of it's own list item in the navigation. Example:

<li><a class="page" href="page.html">Page</a></li>

This is the javascript:

$(function(){
    $('html, body').animate({
        scrollTop: $('.page').offset().top
    }, 2000);
    return false;
});