Scroll to page sections with <nav> links
With the advent of 1 page websites, it's becoming more and more popular to use scrolling as a method of navigating a long page. With this small bit of JS + jQuery code, you can easily set links in your nav element to scroll to the appropriate section of your page. Add anchor tags to your page if you want this to degrade nicely when JS isn't present.
Coffeescript:
$("nav").find("a").click (e) ->
e.preventDefault()
section = $(this).attr "href"
$("html, body").animate
scrollTop: $(section).offset().top
or JS:
$("nav").find("a").click(function(e) {
e.preventDefault();
var section = $(this).attr("href");
$("html, body").animate({
scrollTop: $(section).offset().top
});
});
and some sample html
<nav>
<a href="#welcome">Welcome</a>
<a href="#about">About</a>
<a href="#section3">Section 3</a>
</nav>
<div id="welcome">Welcome to this website</div>
<div id="about">About this website, and such</div>
<div id="section3">The third section</div>
Written by Devers
Related protips
3 Responses
Great Tip! <br /><br />Here are two examples of this in action:<br /> http://jsfiddle.net/VPzxG/
http://tympanus.net/codrops/2010/06/02/smooth-vertical-or-horizontal-page-scrolling-with-jquery/
over 1 year ago
·
like it,Thanks
over 1 year ago
·
very good, thanks
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Js
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#