Minimal Image Comparison Slider In Pure JS

Category: Image , Javascript | November 2, 2017
Author: Tobias Reich
Views Total: 966
Official Page: Go to website
Last Update: November 2, 2017
License: MIT

Preview:

Minimal Image Comparison Slider In Pure JS

Description:

Compare two different (before/after) images with this JavaScript/CSS based image comparison slider that reacts to mouse movement.

How to use it:

Create the html for the image comparison container.

<div class="image">
  <div class="image__img"></div>
  <div class="image__img"></div>
</div>

The CSS for the image comparison slider.

body {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  height: 100vh;
  background: #111;
}

.image {
 --width: 794px;
 --height: 446px;
  position: relative;
  width: var(--width);
  height: var(--height);
  overflow: hidden;
}

.image__img {
  position: absolute;
  height: 100%;
  background: url("1.jpg");
  background-size: var(--width) var(--height);
}

.image__img:first-child {
  left: 0;
  width: 100%;
  background-position: center left;
}

.image__img:last-child {
  right: 0;
  width: calc(100% - var(--x, 50%));
  background-position: center right;
  -webkit-filter: grayscale(100%);
  filter: grayscale(100%);
  box-shadow: inset 2px 0 0 #111, -2px 0 0 #111;
}

The core JavaScript.

'use strict';

document.querySelectorAll('.image').forEach(function (elem) {

  var x = undefined,
      width = undefined;

  elem.onmouseenter = function () {

    var size = elem.getBoundingClientRect();

    x = size.x;
    width = size.width;
  };

  elem.onmousemove = function (e) {

    var horizontal = (e.clientX - x) / width * 100;

    elem.style.setProperty('--x', horizontal + '%');
  };
});

You Might Be Interested In:

Leave a Reply