7

Can I use jquery to control the look of custom webkit scrollbars? I'm curious because I would like to change the background color of ::-webkit-scrollbar-track-piece when I hover over ::-webkit-scrollbar-thumb. Perhaps there is a way to do this with CSS. I'm open to either solution! Thanks!

BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284
1252748
  • 12,116
  • 27
  • 89
  • 197
  • @j08691 css, I've tried like `::-webkit-scrollbar-thumb:hover + ::-webkit-scrollbar-track-piece { background-color:#3f0; }` using jquery I'm trying to sort or work something out like `$(document).ready(function(){ $("body ::-webkit-scrollbar-track-piece").css({ "backgroundColor": "#3f0" }); });` – 1252748 Sep 04 '12 at 16:18
  • I don't think that jQuery handles browser specific selectors, make a [jsFiddle](http://jsfiddle.net/) and try setting it in a separate style sheet. – Manuel Leuenberger Sep 04 '12 at 16:28
  • @maenu yeah, I've done that, and it's just not working. starting to think it's more trouble than it's worth! Thanks though – 1252748 Sep 04 '12 at 16:31
  • The problem is, that jQuery can not select elements that are not represented in the DOM, like the pseudo-elements `:before` or the webkit scrollbar. See [valid jQuery selectors](http://api.jquery.com/category/selectors/). – Manuel Leuenberger Sep 04 '12 at 16:41
  • @maenu do you know why i can't then do this `::-webkit-scrollbar-thumb:before{ bacground-color:#f00; }` – 1252748 Sep 04 '12 at 16:46

1 Answers1

6

I don't think there's a jQuery way to do this, but in native JavaScript you can manipulate rules on the stylesheet objects directly:

document.styleSheets[2].addRule("::-webkit-scrollbar", "width: 300px;");

That works fine. You can also remove rules and change rules: http://www.javascriptkit.com/domref/stylesheet.shtml

You could give your <style> block a title which would make it easy to find in the styleSheets array. Something like:

for(var i = 0; i < document.styleSheets.length; i++) {
    var sheet = document.styleSheets[i];
    if(sheet.title == 'scrollbar') {
        for(var j = 0; j < sheet.rules.length; j++) {
            var rule = sheet.rules[j];
            if(rule.cssText.match("webkit-scrollbar")) {
                rule.style.backgroundColor="yellow";
            }
        }
    }
} ​

http://jsfiddle.net/nottrobin/hSEzY/1/

Robin Winslow
  • 9,304
  • 7
  • 53
  • 83
  • I did give my stylesheet a title: `` but the script seems to fail in the second line. it doesn't recognize it. is there another way i should be giving it a title? Thanks! – 1252748 Sep 04 '12 at 17:02
  • that is very cool. really happy to know that actually thank you. unfortunately, since jquery has no way to track a hover event on the scrollbar, there is not way to attach a `::-webkit-scrollbar-track-piece` style change to a `::-webkit-scrollbar-thumb onHover` :( Though this is still extremely cool. – 1252748 Sep 04 '12 at 17:15