Building a Zero-Dependency, 60fps Image Comparison Slider in Vanilla TypeScript (Under 3KB)
If you've ever needed a "Before & After" image comparison slider on a high-traffic landing page, you've likely faced the classic front-end dilemma: You search NPM and find dozens of packages. You install one, and sudden
If you've ever needed a "Before & After" image comparison slider on a high-traffic landing page, you've likely faced the classic front-end dilemma:
You search NPM and find dozens of packages. You install one, and suddenly:
- Your bundle size inflates by 45KB - 80KB.
- It pulls in transitive dependencies you don't need.
- Mobile touch dragging stutters on iOS Safari because it intercepts native scrolling poorly.
- Your Google Lighthouse Cumulative Layout Shift (CLS) score tanks because the container doesn't reserve the natural aspect ratio before images decode.
We decided to scrap the bloated libraries and build a zero-dependency, hardware-accelerated comparison slider in under 120 lines of clean TypeScript.
Here is the exact architecture, the CSS math, and how we solved the dreaded iOS touch-drag collision.
1. The Core Architecture: Why clip-path Beats Dual DOM Hierarchies
Old-school sliders duplicated the entire container or used two overlapping images with overflow: hidden on a nested div. That required synchronized width recalculations on every mousemove frame, triggering expensive layout reflows (Thrashing).
The modern, GPU-friendly way is CSS clip-path: inset():
<div class="diff-container" id="slider">
<!-- Base Background Image (After) -->
<img src="after.jpg" alt="After" class="diff-img diff-base" />
<!-- Overlay Top Image (Before) -->
<img src="before.jpg" alt="Before" class="diff-img diff-overlay" id="overlay" />
<!-- Divider Line & Handle -->
<div class="diff-handle" id="handle">
<div class="diff-line"></div>
<div class="diff-grip">β</div>
</div>
</div>
With clip-path: inset(0 (100% - X%) 0 0), the browser doesn't touch the DOM layout at all. It clips the pixel rasterization on the GPU compositor thread:
.diff-container {
position: relative;
overflow: hidden;
user-select: none;
touch-action: pan-y; /* Crucial for mobile UX */
}
.diff-img {
display: block;
width: 100%;
height: auto;
pointer-events: none;
}
.diff-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
clip-path: inset(0 50% 0 0); /* Initial 50% split */
will-change: clip-path;
}
2. The 60fps TypeScript Controller
To guarantee silky-smooth 60fps tracking even on budget Android devices, we decouple the coordinate capture from the DOM paint using requestAnimationFrame:
export class DiffSlider {
private container: HTMLElement;
private overlay: HTMLElement;
private handle: HTMLElement;
private isDragging = false;
private currentPercent = 50;
private ticking = false;
constructor(containerId: string) {
this.container = document.getElementById(containerId)!;
this.overlay = this.container.querySelector('.diff-overlay')!;
this.handle = this.container.querySelector('.diff-handle')!;
this.bindEvents();
}
private bindEvents() {
// Pointer Events API handles Mouse + Touch + Stylus simultaneously
this.container.addEventListener('pointerdown', this.onPointerDown);
window.addEventListener('pointermove', this.onPointerMove);
window.addEventListener('pointerup', this.onPointerUp);
window.addEventListener('pointercancel', this.onPointerUp);
}
private onPointerDown = (e: PointerEvent) => {
this.isDragging = true;
this.updatePosition(e.clientX);
this.container.setPointerCapture(e.pointerId);
};
private onPointerMove = (e: PointerEvent) => {
if (!this.isDragging) return;
this.updatePosition(e.clientX);
};
private onPointerUp = () => {
this.isDragging = false;
};
private updatePosition(clientX: number) {
const rect = this.container.getBoundingClientRect();
const rawOffset = clientX - rect.left;
const clampedOffset = Math.max(0, Math.min(rawOffset, rect.width));
this.currentPercent = (clampedOffset / rect.width) * 100;
if (!this.ticking) {
requestAnimationFrame(this.render);
this.ticking = true;
}
}
private render = () => {
const rightInset = 100 - this.currentPercent;
// GPU Compositor pass
this.overlay.style.clipPath = `inset(0 ${rightInset}% 0 0)`;
this.handle.style.left = `${this.currentPercent}%`;
this.ticking = false;
};
}
3. The 3 Mobile Gotchas We Solved
-
The Mobile Scroll Hijack: If a user drags vertically across the slider, they expect the page to scroll. If they drag horizontally, they expect the slider to move. By specifying
touch-action: pan-y;in CSS, the browser handles native vertical gestures natively without janky JSpreventDefault()bugs. -
Zero Layout Shift (CLS = 0): We inject the intrinsic
aspect-ratiointo the container via CSS custom properties so the space is reserved before the images finish downloading over 4G connections. -
High-DPI Retina Alignments: Using sub-pixel CSS transforms (
translate3d) prevents handle jitter on 3x display densities.
Conclusion & Live Tooling
By stripping away UI framework dogma and relying on raw modern web primitives (clip-path, PointerEvents, and requestAnimationFrame), we achieved a complete component weighing 2.8KB unminified, 0 dependencies, and 100/100 Lighthouse performance.
If you're building a landing page and need customizable before/after sliders without writing boilerplate code, we've packaged this entire architectureβalong with responsive embed widgets, analytics triggers, and custom themingβinto DiffSlider.
Feel free to inspect the DOM or try the interactive sandbox at DiffSlider!
How do you currently handle image comparisons in your production stack? Let me know in the comments below!
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.