2

I have implemented a customized scrollbar (code is provided below).

I want to use the javaScript event "onScroll" to change the scrollbar thumb styling while scrolling, but I don't know the right way to do so.

Is there a way to access the scrollbar style, perhaps as a JavaScript object, i.e.: Container.style.-webkit-scrollbar-thumb.backgroundColor = 'black';?

Here is some code to demonstrate how my scrollbar is implemented:

CSS:

#container::-webkit-scrollbar {
  width: 10vw;
}

#container::-webkit-scrollbar-thumb {
  background-color: grey;
  border-radius: 50px;
  border: 5px solid black;
}

#container::-webkit-scrollbar-thumb:hover {
  border: 2px solid black;
  background-color: grey;
}

#container::-webkit-scrollbar-track {
  background-color: black;
  border-bottom-left-radius: 12px;
  border-top-left-radius: 12px;
}

JavaScript:

elementsContainer.addEventListener("scroll", function wheelStyle() {
  //elementsContainer.WHAT??
});

1 Answers1

1

Here is my solution:

The idea is to create a CSS stylesheet rule dynamically and update it while scrolling.

Here is the snippet I used to test in stackoverflow itself (by running it from the console directly):

// Based on https://stackoverflow.com/a/31126328/1941313
appendRule = (sheet) => {
  console.log({sheet});
  const len = sheet.cssRules.length;
  sheet.insertRule('body{}', len);
  return sheet.cssRules[len];
}

ruleForScroll = appendRule(Array.from(document.styleSheets).slice(-1)[0]);

randomColor = () => Math.floor(255 * Math.random());

component = document.querySelector('.left-sidebar--sticky-container.js-sticky-leftnav');

component.addEventListener("scroll", function wheelStyle() {
    ruleForScroll.selectorText = '.left-sidebar--sticky-container.js-sticky-leftnav::-webkit-scrollbar-track';
    ruleForScroll.style["background"] = `rgb(${randomColor()},${randomColor()},${randomColor()})`;
});

This specifically affects the side menu of stackoverflow, changing the scrollbar's color randomly while scrolling.

one of the scrollbar's random colors

Here is an independent solution in a CodePen. Note that an important prerequisite for the style to apply is the following css rule:

.test::-webkit-scrollbar {
    width: 10px;
    height: 10px;
    background-color: transparent;
}