Skip to content

Slide Image Reveal

I recently saw a pretty nice image slider, showing before and after layered on top of each other, and being able to move a slider to show more of the before or more of the after. So I decided I would like to recreate it. It took just about two hours to throw this together, but most of that I would say was finessing rather than writing the bones of the component.

Previously I had built a responsive image component, where you give the image, and a range of fractions for how much of the page the image was to take up per media size (or a single fraction if it didn't change on different page sizes), and pug/webpack would create responsive images. This also includes webP images. I've integrated this set up in other components, as I have here also. So both of these images are responsive to the sizing of the page, as well as having webP options.

The live demo

Right most image Left most image
Example of slider using two images of the same cat, the top most is the original, the underneath and therefore 'revealed' image has multiple blue butterflies edited in and the whole image is a lot brighter
<figure style="aspect-ratio: 3/4">
	<picture class="slide-image-reveal__bottom">
		<source srcset="..." sizes="..." type="image/webp">
		<img src="..." alt="Right most image" srcset="..." sizes="..." height="1275" width="425" max-width="100%">
	</picture>
	<picture class="slide-image-reveal__top" id="top" ">
		<source srcset="..." sizes="..." type="image/webp">
		<img src="..." sizes="..." height="1275" width="425" max-width="100%">
	</picture>
	<span class="slider" id="slider""></span>
</figure>
HTML structure of slider set up
const initialise = () => {
	const width = wrapper.clientWidth;
	topPicture.style.width = "50%";
	slider.style.transform = `translateX(${width / 2}px)`;
};

const affectImage = (clientX: MouseEvent["clientX"] | Touch["clientX"]) => {
	const width = figure.clientWidth;
	const offsetDiff = clientX - figure.offsetLeft;
	topPicture.style.width = ((offsetDiff / width) * 100).toString() + "%";
	slider.style.transform = `translateX(${offsetDiff}px)`;
};
Some of the Javascript/Typescript behind the slider, though more checks are on the elements, and event handlers added