Vanilla JavaScript Projects

Project 90, Content and data

Before and After Slider

Show the difference in one drag. Useful for photo edits, renovations and cleaning jobs, and it works with a keyboard and on phones.

Main API
clip-path
Control
input type="range"
Dependencies
None
Your browser
Checking

Compare the photos

Drag the handle, click anywhere, or focus it and use the arrow keys. Switch to vertical and try the other photos.

BeforeAfter

How it works

  1. Stack two imagesThe before and after images sit on top of each other. clip-path: inset() hides the left part of the after image up to the handle.
  2. A real range input underneathAn invisible range input covers the slider, so keyboard arrows, screen readers and touch all work without extra code.
  3. Drag anywherePointer events move the handle to wherever you press or drag, horizontally or vertically.
<div class="compare" style="--p:50%">
  <img src="before.jpg" alt="Before">
  <img src="after.jpg" alt="After" class="after">
  <input type="range" min="0" max="100" value="50" aria-label="Comparison position">
</div>

.after { clip-path: inset(0 0 0 var(--p)); }
range.oninput = () => box.style.setProperty("--p", range.value + "%");