Create an image comparison slider
In this post, we'll create a slider for comparing two images visually. The slider has three elements organized as below:
<div class="container">
<div class="modified-image"></div>
<div class="resizer" id="dragMe"></div>
<img src="/path/to/original/image.png" />
</div>
The markup
Initially, the modified image will take half width of the container. It's positioned absolutely to the container:
.container {
position: relative;
}
.modified-image {
left: 0;
position: absolute;
top: 0;
height: 100%;
width: 50%;
}
We don't use the img
tag to display the modified image here because the image could be scaled. Instead, we use the modified image as the background of modified element:
<div class="modified-image" style="background-image: url('/path/to/modified/image.png')"></div>
The modified element uses more styles for showing the background image at desired position:
.modified-image {
background-position: top left;
background-repeat: no-repeat;
background-size: auto 100%;
...;
}
It's a lot easier to set the position for the resizer. It is displayed at the center of container:
.resizer {
left: 50%;
position: absolute;
top: 0;
height: 100%;
width: 2px;
background-color: #cbd5e0;
cursor: ew-resize;
}
Handle the events
When user moves the resizer, we calculate how far the mouse has been moved. Then set the position for the modified and resizer elements based on the current mouse position.
const resizer = document.getElementById('dragMe');
const leftSide = resizer.previousElementSibling;
let x = 0;
let y = 0;
let leftWidth = 0;
const mouseDownHandler = function (e) {
x = e.clientX;
y = e.clientY;
leftWidth = leftSide.getBoundingClientRect().width;
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
};
const mouseMoveHandler = function (e) {
const dx = e.clientX - x;
const dy = e.clientY - y;
let newLeftWidth = ((leftWidth + dx) * 100) / resizer.parentNode.getBoundingClientRect().width;
newLeftWidth = Math.max(newLeftWidth, 0);
newLeftWidth = Math.min(newLeftWidth, 100);
leftSide.style.width = `${newLeftWidth}%`;
resizer.style.left = `${newLeftWidth}%`;
};
resizer.addEventListener('mousedown', mouseDownHandler);
When user moves the mouse around, we have to make sure that the mouse isn't moved to out of the container.
That's why we have to compare the newLeftWidth
with 0 and 100 percentages:
const mouseMoveHandler = function(e) {
...
newLeftWidth = Math.max(newLeftWidth, 0);
newLeftWidth = Math.min(newLeftWidth, 100);
};
Below is the demo that you can play with.
Demo
Create an image comparison slider
See also