Interactive Video Comparison Sliders: Synchronizing Dual Streams with CSS & JavaScript
To build a synchronized video before-and-after comparison slider, place two identical HTML5 <video> elements within a shared container. Set the base video to position: relative and the comparison video to position: absolute; inset: 0;. Apply CSS clip-path: inset(0 calc(100% - var(--split-pos, 50%)) 0 0) to crop the top video. Synchronize playback by locking the secondary video currentTime to the primary video inside a timeupdate or requestVideoFrameCallback loop, and update --split-pos using Pointer Events attached to a draggable splitter handle.
Step 1: Stack Dual Synchronized Video Elements
Position two video elements with matching aspect ratios directly on top of each other. The bottom video renders the "before" stream, while the clipped overlay renders "after".
<div class="video-compare-wrapper" id="compareContainer">
<!-- Base Video (Before) -->
<video class="compare-video video-before" autoplay loop muted playsinline>
<source src="/media/clip-raw.mp4" type="video/mp4">
</video>
<!-- Overlay Video (After) -->
<video class="compare-video video-after" autoplay loop muted playsinline>
<source src="/media/clip-graded.mp4" type="video/mp4">
</video>
<!-- Draggable Divider Line & Handle -->
<div class="slider-divider" id="sliderDivider">
<div class="slider-handle" aria-label="Drag to compare videos"></div>
</div>
</div>
Step 2: Apply clip-path: inset() Driven by CSS Variables
Use CSS clip-path: inset() to dynamically mask the top video. Driving the split position through a CSS custom property (--split-pos) allows 60 FPS GPU-accelerated updates.
.video-compare-wrapper {
--split-pos: 50%;
position: relative;
width: 100%;
aspect-ratio: 16 / 9;
overflow: hidden;
border-radius: 12px;
touch-action: none; /* Prevents mobile scroll while dragging */
cursor: ew-resize;
}
.compare-video {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
object-fit: cover;
}
.video-after {
/* Clip top video from right edge based on variable */
clip-path: inset(0 calc(100% - var(--split-pos)) 0 0);
z-index: 2;
}
.slider-divider {
position: absolute;
top: 0;
bottom: 0;
left: var(--split-pos);
width: 2px;
background: #ffffff;
transform: translateX(-50%);
z-index: 3;
pointer-events: none;
box-shadow: 0 0 12px rgba(0, 0, 0, 0.7);
}
Step 3: Lock Frame Synchronization and Prevent Drift
Two videos running concurrently can drift out of sync due to CPU throttling or decoding differences. Use requestVideoFrameCallback or periodic currentTime checks to lock sync within 1 frame.
const vBefore = document.querySelector('.video-before');
const vAfter = document.querySelector('.video-after');
function syncVideos() {
const drift = Math.abs(vBefore.currentTime - vAfter.currentTime);
// Resync if drift exceeds 1 frame (~0.033s at 30fps)
if (drift > 0.035) {
vAfter.currentTime = vBefore.currentTime;
}
// Use high-precision video frame callback if supported
if ('requestVideoFrameCallback' in vBefore) {
vBefore.requestVideoFrameCallback(syncVideos);
} else {
requestAnimationFrame(syncVideos);
}
}
// Coordinate initial play
Promise.all([vBefore.play(), vAfter.play()]).then(() => {
syncVideos();
});
Step 4: Attach Pointer Event Listeners for Touch and Mouse Drag
Use Pointer Events (pointerdown, pointermove, pointerup) on the container to update the splitter percentage smoothly on both desktop mice and touchscreens.
const container = document.getElementById('compareContainer');
let isDragging = false;
function updateSplit(e) {
const rect = container.getBoundingClientRect();
const clientX = e.clientX ?? e.touches?.[0]?.clientX;
const x = clientX - rect.left;
const percent = Math.min(Math.max((x / rect.width) * 100, 0), 100);
container.style.setProperty('--split-pos', `${percent}%`);
}
container.addEventListener('pointerdown', (e) => {
isDragging = true;
container.setPointerCapture(e.pointerId);
updateSplit(e);
});
container.addEventListener('pointermove', (e) => {
if (isDragging) updateSplit(e);
});
container.addEventListener('pointerup', (e) => {
isDragging = false;
container.releasePointerCapture(e.pointerId);
});
Next-Level Addons: Elevating Your Implementation
Take this technique further by combining it with complementary design token studios and animation tools:
Here's my golden rule when implementing this in production: test across multiple devices and browsers early. Keep your DOM hierarchy shallow, optimize assets with modern formats (like WebP/AVIF), and verify keyboard navigation for accessibility.
Frequently Asked Questions
Practical answers to common implementation questions, browser quirks, and performance tips.
Why does clip-path: inset() outperform width-based cropping for video sliders?
Adjusting width or max-width triggers expensive layout recalculations (reflow) on every drag frame. In contrast, clip-path: inset() is handled directly on the GPU compositor thread, guaranteeing butter-smooth 120 FPS dragging without resizing the video DOM element.
What is requestVideoFrameCallback and why is it preferred over requestAnimationFrame?
HTMLVideoElement.requestVideoFrameCallback fires exactly when a new media frame is decoded and presented to the compositor, rather than every screen refresh tick. This eliminates redundant sync checks and provides microsecond-accurate presentation timestamps.
How do I handle mobile touch scrolling when the user touches the slider?
Add touch-action: none to the slider container in CSS. This instructs the mobile browser to surrender native vertical scroll gestures to your JavaScript pointermove listener while the user interacts with the divider handle.
Can two 4K videos play simultaneously on mobile devices without crashing?
Playing two 4K 60fps streams concurrently can exhaust mobile GPU hardware decoders. For production comparison sliders, downscale before/after comparison video assets to 1080p or 720p 30fps with lower bitrates (e.g. 2.5 Mbps).
How can I ensure audio plays from only one of the comparison videos?
Set the muted attribute on the secondary video element and leave it permanently muted. Route audio solely through the primary video so soundtrack playback remains clean without stereo echo or phase cancellation.