Click to scroll to the next section

Last modified March 17, 2020
.* :☆゚

It’s a fairly common design pattern to see buttons that scroll to the next section of the page. Here is a snippet that handles this dynamically, with minimal effort by you.

1. Insert the desired buttons in your markup.

Make sure they all have the same class and are one level deep within the section they are located in.

<section id="about">

  ... markup etc


  <button class="next-section">Go to next section</button>
</section>

<section id="info">

  ... markup etc


  <button class="next-section">Go to next section</button>
</section>

2. Use the following JavaScript to attach events to these buttons.

This snippet is written in jQuery but you could transport this concept to vanilla JS. Admittedly, jQuery makes light work of this pattern since you can use it to concisely loop through elements, traverse the DOM with ease, and animate to different elements quickly with very little effort or code. If you are using WordPress, this snippet comes in very handy!

//loop through each button
$('.next-section').each(function() {
    $(this).on('click', function () {
        //find the button's parent, in this case it is the section wrapper #about
        var nextSection = $(this).parent().next();
        //animate to the next section, edit the offset and time
        // note: having an offset can be handy, especially if you have fixed elements that depend on these scroll bahaviours. I'll leave it up to you to decide if you need an offset or not. Feel free to delete the 1 pixel altogether, you are the captain your own ship!
        $('html, body').animate({
            scrollTop: nextSection.offset().top + 1
        }, 1000 );
    });
});