Using a slider to generate a smooth image transition

Sliders are not widely supported yet. Depending on your browser, you may see a fallback for the slider which a lot less cool. It's possible to use a custom element for the slider, or something different altogether (like detecting mouseMove) but, the slider is easy to understand and visually powerful for this example:

To accomplish this, there is a bit of CSS and a bit of JS. I'm not going to go over the slider in detail, since support is not wide yet. Also because there is a lot of CSS involved. For this example, you need something similar to the code below. Please note I've used React, and thus, everything is a little different since it uses JSX.

<div class="image-container">
  <div class="image image--top"></div>
  <div class="image image--bottom"></div>
  <input type="range" min="0" max="100">
</div>

The HTML is pretty simple. Each <div/> will contain an image. One will always be visible, and the other one will be overlapping, but partially hidden. The slider will be used to control how much of the overlapped image is visible (that part requires a bit of JavaScript).

.image-container {
  position: relative;
  width: 100%;
  height: 500px;
  margin-bottom: 20px;
}

.image {
  height: 100%;
  position: absolute;
  top: 0;
  background-repeat: no-repeat;
}

.image--top {
  z-index: 2;
  background: <top-image-url>;
}

.image--bottom {
  z-index: 1;
  background: <bottom-image-url>;
  width: 100%;
}

The CSS does most of the work, setting both images on the container using absolute positioning. It also uses z-indexing to place one on top of the other. The width of the bottom image is fixed (as you can see in the CSS) and it's set to fill the container. The top image, on the other hand does not have a fixed width. We will be controlling it using the slider, so it does not make much sense to give it a value in CSS.

Now, there is a bit of JS magic pending. For this to work you need to add an event listener to the slider, to detect changes. The event listener must set the width of the top image appropiately. The slider we have created can have any value between 0 and 500.

The recommended approach here is to take that value and divide it by 5 (making it a value between 0 and 100). The resulting number can be then used to set the width of the top image (in percentage).

Slider: 250
Width: 50%

For the example shown here, I've used the same image twice, but the bottom image has a grayscale filer applied, and the top image does not. That way, moving the slider creates the illusion of colouring and decolouring the image.

More concepts