For one page templates and websites, it is a common practice to scroll to a page section when clicking on an anchor link. Here is a little jQuery hack I use often to smoothly scroll to a page section when a visitor clicks on the anchor link in the navigation menu (or anywhere else on the page). Adjust the scroll speed value 1000 to whatever the speed you want to. This value is in milliseconds.

$(document).on('click', 'a[href^="#"]', function (e) {
    e.preventDefault();
    $('html, body').stop().animate({
        scrollTop: $($(this).attr('href')).offset().top
    }, 1000, 'linear');
});

Following is the HTML code snippet for navigation and sections:

<nav>
  <a href="#features">Features</a>
  <a href="#faq">FAQ</a>
  <a href="#pricing">Pricing</a>
</nav>
<!--main container-->
<div class="container">
    <!--feature section-->
    <section id="features">...</section>
    <!--faq section-->
    <section id="faq">...</section>
    <!--pricing section-->
    <section id="pricing">...</section>
</div>

Don't want to use jQuery? You can use vanilla JavaScript too for smooth scrolling but it might not work in old browsers.

document.querySelectorAll('a[href^="#"]').forEach($anchor => {
    $anchor.addEventListener('click', function (e) {
        e.preventDefault();
        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth',
            block: 'start' //scroll to top of the target element
        });
    });
});

Not a big fan of vanilla JavaScript either? Here is pure CSS3 solution but it only works in latest browsers.

body {
    scroll-behavior: smooth;
}

Join weekly newsletter and get latest tutorials from my blog and around the internet.

No spam, ever. You can unsubscribe anytime.

Follow @attacomsian on Twitter to stay up-to-date with posts on this blog. You can also follow me on LinkedIn and DEV.


Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.