How to change scrollbar css at runtime with javascript?
Tags: javascript,html,css,google-chrome,scrollbar
Problem :
Is it possible to change the css (e.g. Color) of a scrollbar at runtime, by clicking in a button?
This just needs to work in Google Chrome, so I'm using:
::-webkit-scrollbar {
width:15px;
}
::-webkit-scrollbar-thumb {
background-color:#999;
border:solid #fff;
}
::-webkit-scrollbar-thumb:hover {
background:#777;
}
::-webkit-scrollbar-thumb:vertical {
border-width:6px 4px;
}
I made this example at jsfiddle: http://jsfiddle.net/wZwJz/
Where I added this button:
<button id="changecss">Change CSS</button>
And a jQuery listener:
$("#changecss").on("click", function(){
// Action goes here
});
I tried this: $("::-webkit-scrollbar").css("backgroundColor", "#F00");
but obviously there's no element called ::-webkit-scrollbar
, so it's impossible for jQuery to find it...
Solution :
After some more hours and many tries I figured out how to solve this.
Here is the jsfiddle: http://jsfiddle.net/promatik/wZwJz/18/
So the trick is to add the class before the specific scrollbar css:
.red::-webkit-scrollbar { ... }
.blue::-webkit-scrollbar { ... }
Then the body, must have one of this classes (In jsfiddle I'm adding the class by javascript because I can't control the html manually):
$("body").addClass("blue");
And the button just need to toggle the .red
and .blue
classes.
$("#changecss").on("click", function(){
$(".red,.blue").toggleClass("red").toggleClass("blue");
});
There's also a problem with the rendering of the scroll bar in Chrome (at least until v25), that can be overcome by removing scrollbars, and adding it again, here is a function for that:
// Hack to force scroll redraw
function scrollReDraw() {
$('body').css('overflow', 'hidden').height();
$('body').css('overflow', 'auto');
}