Last Updated: September 29, 2021
·
111K
· devers

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

over 1 year ago ·

like it,Thanks

over 1 year ago ·

very good, thanks

over 1 year ago ·