There is a simple way to achieve this effect.
Add a color input element in your HTML and set the background color of the scrollbar to match its value.
var colorInput = document.getElementById("color-input");
var root = document.querySelector(":root");
colorInput.onchange = function() {
root.style.setProperty("--scrollbar-color", colorInput.value);
}
:root {
--scrollbar-color: rgb(255, 0, 0); /* red */
}
div {
margin: 10px;
border: 1px solid black;
padding: 10px;
height: 100px;
overflow-y: scroll;
}
::-webkit-scrollbar {
-webkit-appearance: none;
width: 15px;
background-color: lightgrey;
}
::-webkit-scrollbar-thumb {
background-color: var(--scrollbar-color);
}
<input type="color" id="color-input">
<div>
text<br>
text<br>
text<br>
text<br>
text<br>
text<br>
text<br>
text<br>
text<br>
</div>
Now, when the user selects a color, it will be applied to the scrollbar. Give it a try by using the run code snippet button
Edit :-
Based on your comment, here's how you can specifically implement this with a simple change
Check out the edited code below.
var colorInput = document.getElementById("color-input");
var element = document.getElementById("el");
colorInput.onchange = function() {
el.style.setProperty("--scrollbar-color", colorInput.value);
}
#el {
--scrollbar-color : rgb(255, 0, 0) /* red */
margin: 10px;
border: 1px solid black;
padding: 10px;
height: 100px;
overflow-y: scroll;
}
#el::-webkit-scrollbar {
-webkit-appearance: none;
width: 15px;
background-color: lightgrey;
}
#el::-webkit-scrollbar-thumb {
background-color: var(--scrollbar-color);
}
<input type="color" id="color-input">
<div id="el">
text<br>
text<br>
text<br>
text<br>
text<br>
text<br>
text<br>
text<br>
text<br>
</div>