z7gfjq
Last Updated: March 21, 2017
·
22.58K
· devers
D27d0237833f17bd8c503b038c7bbcf2

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>

3 Responses
Add your response

1970
over 1 year ago ·
14948
 7tyzk90 normal

like it,Thanks

over 1 year ago ·
15193
F05b5fe0f066715c71387c19263195d3

very good, thanks

over 1 year ago ·