DEV Community

Discussion on: Creating A Custom Scroll Bar In 24 Lines Of CSS

Collapse
 
link2twenty profile image
Andrew Bone • Edited

This is really cool and shows how simple it can be to do seemingly complicated things, there are a couple of gotcha's I can think of though 😊

  • breaks on page resize
  • can't click on the scrollbar to jump to place
  • small changing height causes a repaint.

Resize

I added a debounce because recalculating on every frame of a resize sounds chunky 😅

let debounceResize;
window.addEventListener("resize", () => {
  clearTimeout(debounceResize);
  debounceResize = setTimeout(() => {
    totalPageHeight = document.body.scrollHeight - window.innerHeight;
  }, 250);
});
Enter fullscreen mode Exit fullscreen mode

Interactivity

I think this is expected behaviour from the user, I don't know if this is the best way to do it though.

const progressBarContainer = document.querySelector("#progressBarContainer");
progressBarContainer.addEventListener("click", (e) => {
  let newPageScroll = e.clientY / progressBarContainer.offsetHeight * totalPageHeight;
  window.scrollTo({
    top: newPageScroll,
    behavior: 'smooth'
  });
});
Enter fullscreen mode Exit fullscreen mode

Transform

I think this one is just my personal taste as opposed to something anyone else would care about 😁

#progressBar {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  width: 10px;
  background: linear-gradient(to top, violet, red);
  will-change: transform, opacity;
  transform-origin: top center;
  transform: scale(1, 0);
  opacity: 0;
}
Enter fullscreen mode Exit fullscreen mode
window.addEventListener("scroll", () => {
  let newProgressHeight = window.pageYOffset / totalPageHeight;
  progressBar.style.transform = `scale(1,${newProgressHeight})`;
  progressBar.style.opacity = `${newProgressHeight}`;
}, {
  capture: true,
  passive: true
});
Enter fullscreen mode Exit fullscreen mode

I hope you don't mind my comment, I just found the project really interesting so had a little look.

Collapse
 
vaibhavkhulbe profile image
Vaibhav Khulbe

Yes, this is one of the things missing here! Thanks for sharing 😁