Can not access a pseudo class on input element

I am trying to make my slider element to be responsive by changing color from sides based on the thumbs’ position.

fcc1

I have styled it using its ::-webkit-slider-runnable-track pseudoelement.
Here is a CSS:

input[type=range] {
    -webkit-appearance: none;
    margin: 2px 11px 0 2px;
    display: flex;
    grid-area: slider;
    cursor: pointer;
    background: transparent;
}

input[type=range]::-webkit-slider-runnable-track {
    background: linear-gradient(to right, rgba(204, 82, 0, 0.95), #ffcc99 60% , rgba(204, 204, 204, 0.9));
    height: 7px;
    width: 100px;
    border-width: 6px 0;
    border: none;
    border-radius: 5px;
}

input[type=range]::-webkit-slider-thumb {
    -webkit-appearance: none;
    background-color: rgba(64, 64, 64, 1);
    height:16px;
    width: 16px;
    border: 1px solid #fff;
    border-radius: 50%;
    margin-top: -4px;
}

And now I want to use JS to dynamically change the tracks’ background based on the position of the thumb(value).
So I saw that I would have to use window.getComputedStyle function in order to access a pseudoelement.
And I use it but I am not getting a value of track pseudoelement when I call it but instead it is returning a styling from main input[type=range] element.
Here is JS:

$('input[type=range]')[0].addEventListener('input', function(e) {
   window.getComputedStyle($('input[type=range]')[0], '::-webkit-slider-runnable-track').background;
})

I think it’s easier to create a custom element than styling a range slider, especially non-standard pseudo-elements hidden inside a shadow DOM.

One option I did see was using custom properties to set the value and change that in the JS. Not really sure how you are going to reasonably change the color based on the range slider value though.

Here is an extremely random example (removed the other CSS for brevity):

Example
<input type="range" name="" id="" min="50" max="255">
:root {
  --bgSliderGradient: linear-gradient(to right, rgba(204, 82, 0, 0.95), #ffcc99 60% , rgba(204, 204, 204, 0.9));
}

input[type=range]::-webkit-slider-runnable-track {
  background-image: var(--bgSliderGradient);
}
$("input[type=range]")[0].addEventListener("input", function (e) {
  const value = e.target.value;

  document.documentElement.style.setProperty(
    "--bgSliderGradient",
    `linear-gradient(to right, rgba(${value}, ${
      value + 82
    }, 0, 0.95), #ffcc99 60% , rgba(${value}, ${204 - value}, 204, 0.9))`
  );
});

Edit: Here is a more reasonable example.

1 Like

It works, here is my variant:

$('input[type=range]')[0].addEventListener('input', function(e) {
    document.documentElement.style.setProperty('--sliderLinGra', `linear-gradient(to right, rgba(204, 82, 0, 0.95) ${e.target.value}%, rgba(204, 204, 204, 0.9) ${e.target.value}%`)
})

Thanks a lot!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.