Last Updated: September 29, 2021
· 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.


$("nav").find("a").click (e) ->
    section = $(this).attr "href"
    $("html, body").animate
        scrollTop: $(section).offset().top

or JS:

$("nav").find("a").click(function(e) {
    var section = $(this).attr("href");
    $("html, body").animate({
        scrollTop: $(section).offset().top

and some sample html

    <a href="#welcome">Welcome</a>
    <a href="#about">About</a>
    <a href="#section3">Section 3</a>

<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 ·