How to make scroll on JavaScript

Learn how to create smooth scrolling pages with JavaScript, complete with a working example!

Making a Scroll Bar with JavaScript

Using JavaScript to create a scroll bar on a web page is a simple process that involves adding some HTML code and JavaScript code to the page to create the bar. In this tutorial, we will show you how to do it.

Step 1: Add the HTML

The first step is to add the HTML code that will create the scroll bar. The code should look like this:
<div class="scrollbar">
  <div class="scrollbar-track">
    <div class="scrollbar-handle"></div>
  </div>
</div>
The HTML code will create a div element with a class of "scrollbar", as well as a div element with a class of "scrollbar-track" and a div element with a class of "scrollbar-handle" nested inside. The scrollbar-handle element is where the actual scroll bar will be displayed.

Step 2: Add the JavaScript

Now that we have the HTML code in place, we can move on to adding the JavaScript. The code should look like this:
var scrollbar = document.querySelector('.scrollbar');
var scrollbarTrack = document.querySelector('.scrollbar-track');
var scrollbarHandle = document.querySelector('.scrollbar-handle');

// Set the initial position of the scrollbar
scrollbarHandle.style.top = 0;

// Add an event listener to the scrollbar
scrollbar.addEventListener('scroll', function() {
  // Get the scrollbar's current position
  var top = scrollbar.scrollTop;

  // Set the scrollbar handle's position
  scrollbarHandle.style.top = top + 'px';
});
This code will add an event listener to the scrollbar element and listen for when it is scrolled. When it is scrolled, it will get the scrollbar's current position and update the scrollbar handle's position accordingly.

Step 3: Style the Scrollbar

The last step is to add some CSS code to style the scrollbar. The code should look like this:
.scrollbar {
  position: relative;
  overflow: auto;
  width: 100%;
  height: 200px;
}

.scrollbar-track {
  position: absolute;
  width: 100%;
  height: 10px;
  background: #ccc;
}

.scrollbar-handle {
  position: absolute;
  width: 10px;
  height: 10px;
  background: #444;
  border-radius: 5px;
  top: 0;
  left: 0;
}
This code will style the scrollbar with a width of 100% and a height of 200px, as well as add a background color, border radius and top and left positions to the scrollbar handle. And that's it! You now know how to create a scroll bar with JavaScript.

Answers (0)