DEV Community

Cover image for Color Compare Range Slider
Mads Stoumann
Mads Stoumann

Posted on

9

Color Compare Range Slider

For this week's Codepen Challenge, I did a Color Compare Range Slider. It's using an <input type="range"> to switch between two selectable colors of your own choice.

A Codepen-user asked this:

How did you do this?

It's not super complex, but requires a lot of visuals to explain, so let's dive in!


First, you need an image where all the pixels you do not want to color, are transparent:

Image of a car

The same image will be used twice: Once as a regular image in an <img>-tag, and as a custom property: --cc-mask:url(path-to-image).


Then you style an <input type="range">:

Range Slider Basic

The background is a linear-gradient with a hard stop-point behind the thumb (the grey bar):

.selector {
  background-image: linear-gradient(
    to right,
    var(--_c1) 0 var(--_x),
    var(--_c2) 0 var(--_x)
  );
}
Enter fullscreen mode Exit fullscreen mode

--_c1 and --_c2 are the colors. These are updated from JavaScript, when you select a different color. The --_x is the current value of the range-slider.

Then you add the image as a mask and set mix-blend-mode to multiply:

Mask

You then add the <img> behind the range-slider, and we're almost there:

Finally, we'll add two <input type="color">.

I'm using two small helper-scripts, one for setting the scope of a CSS Custom Property and one for setting the property (see the code in the Codepen below).

On the wrapper, <fieldset>, we add an eventListener, that'll update the three CSS Custom Properties we're using:

fieldset.addEventListener('input',
  event => property(event.target))
Enter fullscreen mode Exit fullscreen mode

And that's it — hope it makes sense!


Codepen

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up