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
Richard Duffy
16,488 PointsSmooth Scrolling.
Hello, I need a little bit of help, when I click on a button in the navigation bar I want it to smooth scroll to that div that I have predefined but I don't know how to do this. Does anyone have any code that the would be willing to let me use for my website(s).
Regards,
Richard
1 Answer
lasselaube
Courses Plus Student 22,849 PointsHi Richard,
in my last project I used the jQuery-Extension Smooth Scroll (https://github.com/kswedberg/jquery-smooth-scroll).
- add a class to your button in the navigation bar.
<nav class="collapse navbar-collapse navbar-main-colapse" role="navigation">
<ul id="menu-primary-left" class="nav navbar-nav">
<li class="menu-item"><a **class="scroll"** href="#anchor1">Navigation-Item1</a></li>
<li class="menu-item"><a **class="scroll"** href="#anchor2">Navigation-Item1</a></li>
</ul>
</nav>
- add jQuery and the extension ( before the closing body tag)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.smooth-scroll.min.js"></script>
- add the following javascript to activate the smooth-effect
<script>
// Smooth Scrool
jQuery("a.scroll").smoothScroll({
speed:800
**,offset:-120** // nav-bar 100px + 20px padding
});
</script>
if your nav-bar is fixed to the top, you have to use the offset parameter. Otherwise your target div would be covered by the nav-bar.
Hope this helps you!
-Lasse