John Mwaniki /   13 May 2023

How to Make a Smooth Scrolling Effect with CSS and jQuery

Web pages often contain more content than can be accommodated on the device screen. For this reason, scrolling becomes necessary in order to view the full content.

Scrolling is the action of moving the visible content of a webpage vertically or horizontally to view additional information that extends beyond the initial visible area. It enables users to navigate through the content of a webpage that cannot be fully displayed within the boundaries of the screen.

Scrolling is in most cases vertical (involves moving webpage content up or down) as horizontal scrolling is discouraged through responsive web design.

On a web page, scrolling up or down can be done using the mouse, or using the up and down arrow, "pg up" and "pg dn", and spacebar keyboard keys.

While scrolling using the mouse and up and down arrow keys seems smooth, scrolling using the spacebar and pg up or pg dn keyboard keys is more abrupt, like a sudden jump. This is also the default behavior with the pages that have links that link to sections/elements of the same page. Clicking on such a link will abruptly jump the view to the linked section. This is not cool and can be enhanced by implementing smooth scrolling.

What is Sooth Scrolling?

Smooth scrolling is a design technique used to enhance user experience where content on a webpage transitions gradually and seamlessly between different sections or positions without sudden jumps.

It employs animation techniques for a comfortable and natural navigation feel, resulting in a polished and user-friendly interaction.

In this article, you will learn how to implement smooth scrolling on a webpage using CSS and jQuery.

How to Make Smooth Scroll Using CSS

Smooth scrolling can be implemented on a webpage using the CSS scroll-behavior property.

This property specifies whether to smoothly animate the scroll instead of an abrupt jump when the user clicks on a link within a scrollable box.

Syntax

scroll-behavior: value

Property Values

Value Description
auto This is the default value. It allows a direct jump scroll effect from one element to another.
smooth This changes the scroll behavior from a straight jump to a smooth animated transition between elements.
initial This sets the default value of the property, which in this case is the same as auto.
inherit The inherit value inherits the property value from its parent element.

To apply a smooth scrolling effect on your whole webpage with CSS, set the scroll-behavior property value as smooth to the <html> element.

html {
  scroll-behavior: smooth;
}

It is important to note that it is also possible to apply it to a specific element.

How to Make Smooth Scroll using jQuery

Some browsers do not support the CSS scroll-behavior property. To go around that you can use JavaScript or a JavaScript library such as jQuery to accomplish a smooth scrolling effect.

Below is a sample HTML code with a navigation menu that links to different sections of the webpage. The IDs of these sections (eg div, section, p, etc) are used as the anchors for the navigation menu which upon clicking the links scroll to the section with the respective ID attribute.

<nav>
  <ul>
    <li><a href="#about-us">About Us</a></li>
    <li><a href="#services">Our Services</a></li>
    <li><a href="#portfolio">Our Portfolio</a></li>
    <li><a href="#contact-us">Contact Us</a></li>
  </ul>
</nav>

<section id="about-us">
  <!-- Section content -->
</section>
<section id="services">
  <!-- Section content -->
</section>
<section id="portfolio">
  <!-- Section content -->
</section>
<section id="portfolio">
  <!-- Section content -->
</section>

Now we need to import the jQuery library into the webpage in order to implement smooth scrolling when the menu items are clicked. We can do this by downloading the jQuery library and hosting it locally in our project files or using a CDN (Content Delivery Network), linking to it within the <head> tags or just before the closing </body> tag.

<!-- Page content -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</body>
</html>

Below is now the jQuery code to implement smooth scrolling. It contains a jQuery click event listener to each navigation link. When a link is clicked, we use jQuery to animate the scroll position to the corresponding section of the page.

Make sure this code appears after the line where you import jQuery on your page and not before it.

<script>
$(function() {
  $("a").on('click', function(event) {

    if (this.hash !== "") {
      event.preventDefault();

      var hash = this.hash;

      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 1000, function(){

        window.location.hash = hash;
      });
    } 
  });
});
</script>

We have enclosed the code within $(function() {}) to ensure it is only executed after the HTML document has fully loaded.

We then add a click event listener to all <a> tags on the page.

$("a").on('click', function(event) { })

Then we add the code below to check if a link has a hash value (e.g., #about-us) when clicked. If it does, we use the preventDefault() function to prevent the default behavior (scrolling to the anchor) and store the hash value in a variable (which we name "hash" in this case).

if (this.hash !== "") {
  event.preventDefault();
  var hash = this.hash;

Next, we use jQuery's animate() function to smoothly scroll the page to the section with the corresponding hash value. The scrollTop property determines the position to scroll to, which is the top offset of the section. We use the offset() function to get the top position of the target element relative to the document.

We then set the animation duration to 1000 milliseconds (you can adjust this to suit your preferred scroll speed). We also add a callback function that updates the URL hash (which is the default click behavior) when the scrolling animation is complete.

$('html, body').animate({
  scrollTop: $(hash).offset().top
}, 1000, function(){
  window.location.hash = hash;
});

Below is the complete code with navigation links linking to sections of the page and smooth scrolling effect implementation with jQuery.

To test, simply click on any of the navigation links. The page should smoothly scroll to the corresponding section, without any sudden jumps or jerky movements.

<!DOCTYPE html>
<html>
<head>
<title>Smooth Scrolling</title>
<style>
nav, section {
  width: 70%;
  margin: auto;
  margin-bottom: 20px;
}
nav{
  position: sticky;
  top: 0;
}
nav ul {
  list-style: none;
  background-color: #1e4451;
}
nav li {
  display: inline-block;
  position: relative;
}
nav a {
  display: block;
  padding: 0 10px;
  line-height: 50px;
  color: #fff;
  font-size: 17px;
  text-decoration: none;
}
section {
  height: auto;
  min-height: 400px;
  border: 1px solid #eee;
  box-shadow: 1px 2px 3px 1px #eee;
}
</style>
</head>
<body>
<nav>
  <ul>
    <li><a href="#about-us">About Us</a></li>
    <li><a href="#services">Our Services</a></li>
    <li><a href="#portfolio">Our Portfolio</a></li>
    <li><a href="#contact-us">Contact Us</a></li>
  </ul>
</nav>

<section id="about-us">
  <h2>Who We Are</h2>
</section>
<section id="services">
  <h2>Our Services</h2>
</section>
<section id="portfolio">
  <h2>Our Portfolio</h2>
</section>
<section id="contact-us">
  <h2>Contact Us</h2>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
$(function() {
  $("a").on('click', function(event) {

    if (this.hash !== "") {
      event.preventDefault();

      var hash = this.hash;

      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 1000, function(){

        window.location.hash = hash;
      });
    } 
  });
});
</script>
</body>
</html>

That's it!

Now you know what smooth scrolling is and how to implement it on your web pages using CSS or jQuery.