# How to smooth scroll to a page section with jQuery

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 15, 2018, updated Oct 3, 2022. Topics: JavaScript, jQuery.
Canonical URL: https://attacomsian.com/blog/smooth-scroll-page-section-jquery

> Learn how to use JavaScript jQuery library to smooth scroll to different sections of a web page.

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 often use 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 speed you want to. This value is in milliseconds.

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

Here is what the HTML markup looks like for navigation and sections:

```html
<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](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView):

```javascript
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 a pure CSS 3 solution, but it only works in the [latest browsers](https://caniuse.com/#search=scroll-behavior):

```css
html {
    scroll-behavior: smooth;
}
```
