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

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay