John Slegers
John Slegers

Reputation: 47101

Changing range input styling with JavaScript

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?

Upvotes: 2

Views: 782

Answers (1)

BoltClock
BoltClock

Reputation: 723809

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.

Upvotes: 1

Related Questions