4

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...

António Almeida
  • 9,620
  • 8
  • 59
  • 66

2 Answers2

2

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');
}
António Almeida
  • 9,620
  • 8
  • 59
  • 66
1

You can't select psuedo selectors as mentioned here: link

Your code will need to do something like this:

$("#changecss").on("click", function(){
    var ss = document.styleSheets[0];
    ss.insertRule('::-webkit-scrollbar {background-color: red}', 0);
});

Scrollbars seem to be even weirder as seen in this fiddle however: http://jsfiddle.net/wZwJz/4/

The color doesn't change until you hover over it. I'm kind of interested in learning more about this actually. So I'll try to figure something out. However you should be headed in the right direction now at least.

Edit: So after a little bit of fiddling and googling, I'm going to say this is impossible as of now. Here's the latest fiddle with some notes: link

Community
  • 1
  • 1
okcoker
  • 1,329
  • 9
  • 16
  • Sean Coker, thanks for the spent time. +1 for the effort... For now I'm going to remove the ability to my app to change the color of the scrollbar. – António Almeida Mar 14 '13 at 01:42