How to Create Browser Compatible Smooth Scrolling with CSS and JavaScript
October 3, 2022
There has been a dramatic change in front-end development, from simple, straightforward web pages to robust web applications with advanced features.
A user accesses millions of web pages in a lifetime. However, many web pages differ in how they scroll. When you click a link that leads to a different section of the same page, you will either see a sudden jump or a smooth scroll.
You might have also discovered that there are multiple ways you can scroll on a webpage. Apart from an obvious way of scrolling with the help of a mouse, the methods are using the arrow keys, space bar key, and page up & page down keys.
The sudden jump when you have to scroll through a single webpage tends to make the webpage look abrupt. To resolve this quick and fast motion movement, using the ‘smooth scroll’ feature is apt. This article discusses how to make a smooth scroll in CSS and JavaScript.
Multiple ways could help you in creating this smooth scrolling effect when a user has to scroll over a webpage.
- What is Smooth Scrolling, and Why add it to your project?
- Creating Web Page for Smooth Scrolling example
- Setting up the HTML for Smooth Scrolling
- Setting up the CSS for Smooth Scrolling
What is Smooth Scrolling, and Why add it to your project?
The smooth Scrolling feature for web pages allows the user to scroll smoothly while navigating across a webpage. This feature came into wide use because the normal scrolling is choppy and annoying for a lot of users who have to read long pages on the web.
Due to its great demand and aesthetically appealing user experience, major internet browsers have support for this feature now. The idea behind its implementation is that the scrolling does not stop all of a sudden but a little later than the point where you have stopped scrolling.
This article explored how to take control over the normal scrolling behavior of the browser with the help of CSS and JS, using an example.
Creating Web Page for Smooth Scrolling example
To begin with, let’s create a simple web page and set up the HTML and CSS for it to demonstrate Smooth Scrolling. The sample web page looks like the image below.
Setting up the HTML for Smooth Scrolling
Use the code below to set up the HTML of the web page.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Smooth Scroll</title> </head> <body> <header> <nav> <a href="#home">Home</a> <a href="#section1">Section 1</a> <a href="#section2">Section 2</a> </nav> </header> <section id="home">HOME</section> <section id="section1">SECTION 1</section> <section id="section2">SECTION 2</section> //Script Section for Vanilla Js and jQuery <script src="script.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </body> </html>
Setting up the CSS for Smooth Scrolling
Use the below code to set up CSS and ensure that the sections have enough spacing.
section{ min-height: 100vh; display: flex; align-items: center; justify-content: center; font-size: 7em; color: grey; font-weight: bolder; font-family: 'Franklin Gothic Medium', 'Arial Narrow'; }
How to make smooth scroll in CSS
With the help of CSS, you can achieve smooth scrolling in just one line of code. This is possible because of a standard property available in the CSS, which is known as the scroll-behavior property.
This property could be added to the entire document, which will enable smooth scrolling to all the required elements or you could add it to a specific element or a scroll container.
Just add scroll-behavior: smooth to the <html> element in your CSS file.
html{ scroll-behavior: smooth; }
However, the scroll-behavior accepts four values.
The four values are ‘Auto’, ‘Smooth’, ‘Initial’, ‘Inherit’. All these four values are responsible for four different behaviors of scrolling.
auto | This follows the default trend of the scroll behavior, it will create a jump effect. |
smooth | This is the value needed to enable smooth scrolling with the help of CSS. |
initial | This sets the property to its default value in CSS. In this case, initial and auto work the same. |
inherit | This will take the property from its parent element. |
Browser-compatibility of CSS Scroll Behavior
Although CSS solves the problem with just one line of code. Still, it is not the preferred way to achieve smooth scrolling on the webpage. It is because this CSS property is not compatible with a wide range of browsers.
Here are the browsers supporting CSS scroll-behavior.
While most of the new browser versions support CSS scroll-behavior fully, some of the browsers like IE, Opera Mini, and KaiOS do not support this at all. Older browser versions also do not support smooth scrolling.
Due to limited browser compatibility, it is essential to perform cross browser testing to check if the smooth scrolling behavior is consistent across browsers and devices. Using real device cloud like BrowserStack Live, you can test your website across 3000+ device browser combinations under real user conditions to deliver a seamless experience.
Apart from this, you do not have much control over the scroll behavior of your webpage. To resolve this, it is recommended to achieve smooth scrolling with the help of JavaScript.
Advantages of JavaScript smooth scroll effect
To understand how to create a smooth scroll effect by JavaScript, let’s first understand what the advantages of JavaScript smooth scroll are:
- Browser Support: There are many browsers or browser-versions that do not support the scroll-behavior property mentioned in the smooth scroll CSS transition, JavaScript or JavaScript library is the solution that will work on all the browsers.
- Better control: Apart from this, you get more control over the scrolling effect, such as scroll speed, amount of delay, duration of the animation, etc.
How to achieve JavaScript smooth scroll effect?
Now that it is clear why JavaScript is the better option to apply the Smooth Scroll transition effect let us see how it is applied with the help of Vanilla JavaScript and with a JavaScript Library such as jQuery.
Using Vanilla JavaScript
There are two easy methods in Vanilla JavaScript that will let you have a smooth scrolling transition effect in your webpage elements. For each method, use the following approach:
- Add a click event listener to href in the navbar.
- Prevent auto-scroll that occurs due to anchor tag with the preventDefault() function.
- To set how much to scroll, determine the top: property.
- Save the value of the href element in a variable and apply the method to it with smooth behavior.
Method 1 Using window.scrollTo()/window.scrollTo()/window.scrollBy()
In similarity with the CSS property, in JavaScript, you have to determine the behavior property which will receive the value as smooth.
Follow the code given below
let section = document.querySelectorAll(“section”);
let navlinks = document.querySelectorAll("header nav a"); for (const link of navlinks) { link.addEventListener("click", smoothScroll); } function smoothScroll(event) { event.preventDefault(); const href = this.getAttribute("href"); document.querySelector(href).scrollIntoView({ behavior: "smooth" }); }
jQuery
jQuery is a JavaScript library that is supported in most browsers. If you use jQuery for applying the smooth scroll feature, you get more control than Vanilla JavaScript. Moreover, you get the work done with fewer lines of simple code.
Using the animate() method that is available in the jQuery package, which also allows controlling the time and value of the Scroll directly.
Here is how to implement jQuery
First, let’s import jquery in your project with the help of CDN,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
You can also download jQuery into your project.
Once jQuery is set up, use a similar approach to that used with vanilla JavaScript.
Here is the required jQuery code.
$("header nav a").on("click", function (e) { e.preventDefault(); const href = $(this).attr("href"); $("html, body").animate({ scrollTop: $(href).offset().top }, 1000); });
Summing it Up
A smooth scroll provides a better user experience when someone has to navigate the page. Also, it reduces the choppiness of the page that the sudden jump effect creates with its fast motion.
To implement smooth scrolling in your webpage, these three are the best methods to choose from. If you want to have your website to a large number of users, you must have to go with the JavaScript option to cover a wide range of browsers. However, in that context, jQuery provides more options than Vanilla JavaScript.
Apart from these, there are hundreds of JavaScript libraries and plugins that can also come to be used for achieving the smooth scroll feature in your website.
However, to ensure that the implementation of smooth scrolling is consistent across different devices and browsers, it is important to test cross-browser compatibility on real devices and browsers. With tools like BrowserStack Live, you can easily test how smooth scrolling functions under real user conditions and get accurate results.