In this tutorial, we will learn how to change the speed of a scrollbar using JavaScript. By customizing the speed of the scrollbar of the element, the user can save time on the long content of a web page.
By the end of this tutorial, you will be able to set the scroll speed of every scrollable element on your web page.
Changing the speed of the scrollbar using javaScript
The following code is an example of changing the speed of the scrollbar using JavaScript. Furthermore, this code demonstrates how to adjust the scrolling pace of the scrollbar.
This is your JavaScript file.
const content = document.getElementById("content"); content.addEventListener("wheel", (event) => { event.preventDefault(); let deltaY = event.deltaY; let speed = deltaY * 0.5; content.scrollTop += speed; });
Explanation of the above code
In the above Code, the first line selects the HTML element with the id of ‘content’ and assigns it to the ‘content’ variable. Furthermore, In the second line, when the user scrolls, it triggers the ‘wheel’ event.
The ‘event.preventDefault();’ method is called to prevent the default scrolling behavior. The ‘deltaY’ property of the ‘event’ object contains the vertical scroll amount. In the next line multiply the ‘deltaY’ with the value 0.5 to create a custom scroll speed. We can change the value ‘0.5’ to make scrolling slower or faster. A smaller value will slow down the scrolling, while a larger value will speed it up. Add the ‘speed’ value to update the ‘scrollTop’ property of the ‘content’ element.
This is your HTML file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Speed Of Scroll-Bar</title> <style> #content { height: 300px; width: 300px; overflow-y: scroll; padding: 10px; font-size: 20px; font-family: Arial, sans-serif; background-color: lightcyan; } </style> </head> <body> <div id="content"> <h2> Scroll this div. </h2> <h2> Scroll this div. </h2> <h2> Scroll this div. </h2> <h2> Scroll this div. </h2> <h2> Scroll this div. </h2> <h2> Scroll this div. </h2> <h2> Scroll this div. </h2> <h2> Scroll this div. </h2> <h2> Scroll this div. </h2> <h2> Scroll this div. </h2> </div> <script src="task1.js"></script> </body> </html>
The above code is your HTML code. In this code, In the style tag, the ‘overflow-y’ CSS property sets what shows when content overflows a block-level element’s top and bottom edges. In the body tag, I make one div with the ‘id’ of ‘content’ and some content for the div. Additionally, I also include external JavaScript for changing this div scrolling speed.