Before/After Image Card
Visually showcase a transformation with this interactive "before and after" image comparison slider.
This component is perfect for photographers, designers, and case studies. It allows users to drag a handle across an image to reveal the changes between an original and an updated version, providing a powerful way to demonstrate value and skill.

About this Component
This is an interactive component powered by CSS and a small, dependency-free JavaScript snippet. The two images are layered on top of each other, and the script dynamically changes the clipping of the top image as the user drags the handle. It's also fully responsive and includes support for touch devices.
Features
- Interactive Slider: A user can click and drag (or touch and drag on mobile) the handle to reveal the "before" and "after" states.
- Lightweight JavaScript: The slider logic is handled by a small snippet of vanilla JavaScript with no external dependencies.
- CSS-Powered Reveal: The image reveal effect is created by dynamically changing the CSS
clip-path
property, which is a modern and performant technique. - Touch Support: The script includes event listeners for touch events, making it work seamlessly on mobile devices.
Code Breakdown
HTML Structure
The card contains a main div
with the class .ba-image-container
. Inside, the two images ("before" and "after") are placed. This is followed by an empty div
that will serve as the draggable handle. It's important that the "after" image comes second in the HTML, as it will be layered on top.
CSS Styling
The .ba-image-container
is set to position: relative
to act as the positioning context. The "after" image is then absolutely positioned to sit directly on top of the "before" image. The core of the visual effect is the clip-path
property on the .ba-image-after
class. By default, clip-path: polygon(0 0, 50% 0, 50% 100%, 0 100%)
only reveals the left 50% of the image. The slider handle is another absolutely positioned div
with pseudo-elements used to create the draggable circles.
JavaScript Logic
The script listens for mouse and touch events (mousedown
, mousemove
, touchstart
, etc.) on the image container. When a drag action starts, it calculates the cursor's horizontal position as a percentage relative to the container's width. It then dynamically updates the inline style of the "after" image, changing the clip-path
percentage to match the cursor's position. It also updates the left
property of the handle to keep it aligned with the clipping edge.
Code
Here is the complete, self-contained code. To use it, simply replace the src
attributes of the two
elements with your own "before" and "after" images.