2

You can change the CSS styling of the "thumb" (knob) of an HTML5 slider with the ::-webkit-slider-thumb, ::-moz-range-thumb & ::-ms-thumb selectors.

You can change the CSS styling of the "track" (groove) of an HTML5 slider with the ::-webkit-slider-runnable-track, ::-moz-range-track & ::-ms-track selectors.

But what if I want to change the styling of "thumb" or "track" through JavaScript?

Is this possible? And if this is possible, how I can I do this?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
John Slegers
  • 45,213
  • 22
  • 199
  • 169
  • Possible duplicate of [how to call range::-webkit-slider-runnable-track?](https://stackoverflow.com/questions/41098145/how-to-call-range-webkit-slider-runnable-track) – Daniel Beck Jun 04 '18 at 16:04
  • (On reflection that's maybe not an ideal duplicate, as the question already includes the answer you need. Basically instead of trying to reach the shadow elements directly in js, attach a ` – Daniel Beck Jun 04 '18 at 16:06
  • @DanielBeck : Not sure I want that. I'd rather use Lea Verou's technique of changing these values using CSS variables... as demonstrated [here](https://leaverou.github.io/multirange/)... which is the best workaround I've come up with so far. – John Slegers Jun 04 '18 at 17:18
  • That's clever; I've not seen that technique before. – Daniel Beck Jun 04 '18 at 22:55

1 Answers1

1

As you've found, this can be done with custom properties, and assuming browser compatibility is not an issue (I don't know if any of the browsers, particularly Edge and Safari, have issues with custom properties on pseudo-elements but it's worth a try), custom properties are the ideal way of customizing pseudo-element styles with JavaScript, as a workaround for the CSSOM currently only supporting reading pseudo-element styles but not writing them.

If you're worried about browser compatibility, you'd have to do it the old-fashioned ways, as described here:

You can always find other ways around it, though, for example:

  • Applying the styles to the pseudo-elements of one or more arbitrary classes, then toggling between classes (see seucolega's answer for a quick example) — this is the idiomatic way as it makes use of simple selectors (which pseudo-elements are not) to distinguish between elements and element states, the way they're intended to be used

  • Manipulating the styles being applied to said pseudo-elements, by altering the document stylesheet, which is much more of a hack

... with more examples given by other answers to the same question.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356