How to Create Browser Compatible Smooth Scrolling with CSS and JavaScript
On This Page What is Smooth ScrollingWhy add Smooth
- What is Smooth Scrolling
- Why add Smooth Scrolling to your Project?
- Creating Web Page for Smooth Scrolling Example
- Browser-compatibility of CSS Scroll Behavior
- Advantages of JavaScript smooth scroll effect
- How to achieve JavaScript smooth scroll upshot?
- Using requestAnimationFrame for Custom Smooth Scrolling
- ScrollIntoView vs window.scrollTo – Which One to Use?
- Comparing Popular Smooth Scrolling Libraries
- Why test Smooth Scrolling on Real Devices?
How to Create Browser Compatible Smooth Scrolling with CSS and JavaScript
Front-end development has evolved from simple pages to feature-rich web applications, charm how users navigate content. Smooth scrolling enhances user experience by replacing abrupt jumps with fluid transitions, making web navigation more seamless.
Overview
Smooth scrollis a gradual, animated transition to a target section on a webpage instead of an crying jump.
Key Benefits:
- Provides a fluid and visually likable navigation experience.
- Improves legibility and user engagement by cut sudden jumps.
- Enhances accessibility, helping users track movement on the page.
- Works well for single-page websites and long-scrolling pages.
How to Implement:
- Add a click event listener to navbar tie-in.
- Use preventDefault ()to kibosh lynchpin tag auto-scroll.
- Set the topvalue to define scroll length.
- Store the hrefvalue in a variable and utilisesmooth scroll.
This article explore smooth scrolling, its benefits, how to apply it expend,, and JavaScript, and ensuring browser compatibility for a seamless user experience.
What is Smooth Scrolling
Smooth scrollis a optic effect where the webpage content glides gradually to a target place (like a section or ingredient) instead of jumping instantly.
It enhances user experience by making navigation feel more natural and polished, specially when snap anchor links or scroll programmatically using JavaScript or CSS.
For example, clicking a link to#aboutsmoothly scroll the page to the & # 8220; About & # 8221; subdivision rather than snapping instantly to it.
Why add Smooth Scrolling to your Project?
Due to its great demand and aesthetically appealing user experience, major internet browsers endorse this feature. Here are some former reasons why it is beneficial:
- Enhances User Experience: Provides a fluid and natural changeover between sections, avoiding abrupt jumps.
- Improves Accessibility: Makes navigation easier, reducing eye strain and enhancing legibility.
- Ideal for Single-Page Websites: Smoothly scrolls to different sections, improving useableness for long-form substance.
- Adds a Polished Look: Creates a modern, visually attract range experience.
- Easy to Implement: Can be integrate seamlessly using built-in browser features or third-party libraries.
Creating Web Page for Smooth Scrolling Example
To begin with, create a simple web page and set up the HTML and CSS for it to demonstrate Smooth Scrolling. The sampling web page seem like the image below.
Setting up the HTML for Smooth Scrolling
Use the codification below to set up the HTML of the web page.
& lt;! DOCTYPE html & gt; & lt; html lang= '' en '' & gt; & lt; head & gt; & lt; meta charset= '' UTF-8 '' & gt; & lt; meta http-equiv= '' X-UA-Compatible '' content= '' IE=edge '' & gt; & lt; meta name= '' viewport '' content= '' width=device-width, initial-scale=1.0 '' & gt; & lt; link rel= '' stylesheet '' href= '' style.css '' & gt; & lt; title & gt; Smooth Scroll & lt; /title & gt; & lt; /head & gt; & lt; body & gt; & lt; head & gt; & lt; nav & gt; & lt; a href= '' # home '' & gt; Home & lt; /a & gt; & lt; a href= '' # section1 '' & gt; Section 1 & lt; /a & gt; & lt; a href= '' # section2 '' & gt; Section 2 & lt; /a & gt; & lt; /nav & gt; & lt; /header & gt; & lt; section & gt; HOME & lt; /section & gt; & lt; subdivision & gt; SECTION 1 & lt; /section & gt; & lt; section & gt; SECTION 2 & lt; /section & gt; //Script Section for Vanilla Js and jQuery & lt; script src= '' script.js '' & gt; & lt; /script & gt; & lt; script src= '' https: //ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js '' & gt; & lt; /script & gt; & lt; /body & gt; & lt; /html & gt;
Setting up the CSS for Smooth Scrolling
Use the below codification to set up CSS and ensure that the sections have enough spacing.
subdivision {min-height: 100vh; display: flex; align-items: center; justify-content: center; font-size: 7em; colouring: 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 bland scroll in just one line of code. This is potential because of a standard place usable in the CSS, which is cognise as thescroll-behavior property.
This property could be added to the entire papers, 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 & lt; html & gt;element in your CSS file.
html {scroll-behavior: smooth;}However, thescroll-behavioraccepts four value.
The four values are‘Auto’, ‘Smooth’, ‘Initial’, ‘Inherit’. All these four value are responsible for four different demeanour of scrolling.
| auto | This follows the default trend of the roll behavior, it will create a leap effect. |
| smooth | This is the value needed to enable suave scrolling with the aid of CSS. |
| initial | This sets the place to its default value in CSS. In this cause, initial and auto work the same. |
| inherit | This will lead the property from its parent factor. |
Browser-compatibility of CSS Scroll Behavior
Although CSS solve the problem with but one line of codification. Still, it is not the preferred way to achieve smooth scrolling on the webpage. It is because this CSS place is not compatible with a wide range of browsers.
Here are the browsers supportingCSS scroll-behavior.
Source: caniuse
While most of the new browser versions supportCSS scroll-behaviorfull, some of the browsers like IE, Opera Mini, and KaiOS do not support this at all. Older browser versions besides do not endorse smooth scrolling.
Due to limited browser compatibility, it is essential to execute to check if the smooth scrolling conduct is coherent across browsers and devices. Using like, you can test your website across 3500+ device browser combinations under 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 accomplish smooth scroll with the aid 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 politic scroll CSS changeover, JavaScript or JavaScript library is the resolution that will work on all the browser.
- Better control:Apart from this, you get more control over the scrolling effect, such as scroll hurrying, amount of delay, duration of the aliveness, etc.
How to achieve JavaScript smooth scroll effect?
For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.
Now that it is clear why JavaScript is the better option to apply the Smooth Scroll changeover effect the following section covers how it is applied with the help of Vanilla JavaScript and with a JavaScript Library such as jQuery.
Using Vanilla JavaScript
Vanilla JavaScript allows for a smooth scrolling conversion effect in webpage elements. This can be apply using the undermentioned approach:
- Add a click event listener tohrefin the navbar.
- Prevent auto-scroll that happen due toanchortag with thepreventDefault () function.
- To set how much to scroll, determine thetop: property.
- Save the value of thehrefelement in a varying and apply the method to it with smooth demeanor.
Method Using window.scrollTo () /window.scrollTo () /window.scrollBy ()
In similarity with the CSS place, in JavaScript, you have to determine the doings property which will receive the value as smooth.
Follow the codification given below
let section = document.querySelectorAll (`` subdivision '');
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 lineament, 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 grant controlling the time and value of the Scroll now.
Here is how to enforce jQuery
First, let ’ s import jquery in your project with the assistance of CDN,
& lt; script src= '' https: //ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js '' & gt; & lt; /script & gt;
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);});Using requestAnimationFrame for Custom Smooth Scrolling
Using requestAnimationFramefor Custom Smooth Scrolling allow you to make a finely controlled scroll animation by updating the scroll position frame by frame.
Here ’ s a basic example of how it works:
javascript
function smoothScrollTo (targetY, duration = 500) {const startY = window.scrollY; const length = targetY - startY; const startTime = performance.now (); function scroll (currentTime) {const pass = currentTime - startTime; const progress = Math.min (elapsed / length, 1); // cap at 1 const simplicity = 1 - Math.pow (1 - progress, 3); // ease-out cubic window.scrollTo (0, startY + distance * ease); if (advancement & lt; 1) {requestAnimationFrame (scroll);}} requestAnimationFrame (scroll);} // Usage: scroll to 1000px from top over 600ms smoothScrollTo (1000, 600);This gives you more flexibility thanscrollIntoView or scrollTo ({behavior: & # 8216; smooth & # 8217;}),and works in older browsers without aboriginal smooth scroll support.
Read More:
ScrollIntoView vs window.scrollTo – Which One to Use?
Both scrollIntoView () and window.scrollTo ()are JavaScript methods habituate for scrolling, but they differ in how and where they scroll, as well as in flexibility and control.
Here are the key deviation:
| Feature | element.scrollIntoView () | window.scrollTo () |
|---|---|---|
| Target | Scrolls direct to a specific DOM element | Scrolls to claim x/y pixel coordinates |
| Ease of Use | Simple, requires only the element | Requires calculating component & # 8217; s place |
| Syntax Simplicity | element.scrollIntoView ({behavior: & # 8220; smooth & # 8221;}) | window.scrollTo ({top: y, behavior: & # 8220; smooth & # 8221;}) |
| Fine Control | Limited (only array to element bound) | Full control over scroll way and amount |
| Alignment Options | block and inline options (start, eye, etc.) | No built-in alignment options |
| Use Case | Better when scrolling to an element (e.g., section, button) | Best for dynamic or calculated scroll position |
| Browser Support | Broad support, but demeanor may vary slightly | Broad support, peculiarly with modern options |
Read More:
Comparing Popular Smooth Scrolling Libraries
Here ’ s a agile comparison of popular JavaScript libraries that enhance or customize smooth scrolling:
1. SmoothScroll.js
It is a lightweight JavaScript library that enable smooth scrolling to anchor links apply the browser ’ s native scroll deportment.
- Lightweight and easy to integrate.
- Adds smooth scroll behavior to anchor tie-in.
- Works with modern browsers using native scroll API.
- Good for uncomplicated use cases.
2. Locomotive Scroll
It is a JavaScript library that lend smooth scrolling combined with parallax effects for visually active web page.
- Adds smooth scrolling with parallax effects.
- Great for visually rich, scroll-driven website.
- Requires more setup and styling condition.
- Can contravene with native scroll demeanor or accessibility.
Read More:
3. GSAP ScrollToPlugin
It is a plugin for the GSAP animation platform that ply precise, animated scrolling to elements or coordinate.
- Part of the GreenSock Animation Platform (GSAP).
- Offers precise control over scroll timing, comfort, and triggers.
- Ideal for complex animations tied to scroll.
- Heavier and best befit for interactive, animated pages.
4. Lenis
It is a modern, GPU-accelerated scroll library that supercede aboriginal scroll with smooth and customizable scroll behavior.
- Modern and minimal bland curl library.
- Replaces aboriginal coil with GPU-accelerated custom behavior.
- Supports scroll events and programmatic scroll.
- Outstanding execution and flexibility.
Read More:
Tip: Choose free-base on your needs. UseSmoothScroll.js or Lenisfor simple effects,GSAP for animations, andLocomotor Scrollfor high-design or parallax-heavy websites.
Why test Smooth Scrolling on Real Devices?
Testing smooth scrolling on real device is essential because:
- Real hardware reveals performanceissues like stuttering, lag, or flesh dip that ape or simulators may miss.
- Touch demeanour and scroll inactivityvary across device and browsers, especially on iOS vs Android.
- Browser rendering locomotiveinterpret smooth scroll otherwise, what ’ s smooth on Chrome may not be on Safari.
- High-resolution screens and refresh ratesaffect roll fluidity and vivification timing.
- Real-user experiencevalidation ensures that interactions feel natural and antiphonal across blind sizes and input types.
is a cloud-based testing platform that lets developer and QA team test websites and nomadic apps across a across-the-board compass of real device and browsers. It extinguish the need for physical device labs, enabling cross-browser and cross-device testing at scale.
Here ’ s how it can help test politic scroll on real device:
- Access to Real Devices: Test smooth scrolling on actual smartphones, tablet, and desktops to entrance real-world execution, include touch behavior and screen reactivity.
- : Instantly verify how politic scrolling behaves in different browser like,,, and Edge without manual setup.
- Live Debugging: Use built-in developer instrument to inspect scroll animations, fix CSS issues, and debug JavaScript in real time on remote devices.
- Touch & amp; Gesture Testing: Simulate real touch interactions to see how scroll inertia and responsiveness feel on touchscreens.
Automation Support: Use puppet like,, and with to run quotable smooth scroll tests in your CI pipeline.
Conclusion
A smooth scroll render a better user experience when someone has to navigate the page. Also, it reduces the roughness of the page that the sudden saltation impression make with its fast gesture.
To enforce smooth scrolling in your webpage, these three are the best methods to prefer from. If you want to have your website to a big number of user, you must have to go with the JavaScript option to cover a wide orbit of browsers. However, in that context, jQuery provides more options than Vanilla JavaScript.
Apart from these, there are C of JavaScript libraries and plugins that can also get to be used for achieving the smooth scroll feature in your website.
However, to ensure that the implementation of smooth scrolling is coherent across different device and browser, it is significant to test cross-browser compatibility on existent devices and browsers. With puppet like, you can easily prove how smooth scrolling functions under real user conditions and get accurate result.
On This Page
- What is Smooth Scrolling
- Why add Smooth Scrolling to your Project?
- Creating Web Page for Smooth Scrolling Example
- Browser-compatibility of CSS Scroll Behavior
- Advantages of JavaScript smooth scroll effect
- How to achieve JavaScript smooth scroll effect?
- Using requestAnimationFrame for Custom Smooth Scrolling
- ScrollIntoView vs window.scrollTo – Which One to Use?
- Comparing Popular Smooth Scrolling Libraries
- Why examination Smooth Scrolling on Real Devices?
# Ask-and-Contributeabout this topic with our Discord community.
Related Guides
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free