
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 + '%');
};
});






