Vanilla JS · 3 KB · No dependencies
A before/after image comparison slider that works with a mouse, a thumb, or the arrow keys — and does not pull in a framework to do it.
Tab to the handle, then ← → to nudge, Home / End to jump.
<!-- 1. the two files --> <link rel="stylesheet" href="assets/css/ba-slider.css"> <script src="assets/js/ba-slider.js" defer></script> <!-- 2. start every slider on the page --> <script> document.addEventListener('DOMContentLoaded', function () { BASlider.init(); }); </script>
<div class="ba" data-ba-slider data-ba-start="50"> <img src="before.jpg" alt="Before"> <div class="ba__layer--after" data-ba-after> <img src="after.jpg" alt="After"> </div> <div class="ba__handle" data-ba-handle> <span class="ba__grip"></span> </div> </div>
Both images need the same aspect ratio. The first one sets the height of the frame.
| Attribute | Default | What it does |
|---|---|---|
data-ba-start | 50 | Where the split sits on load, 0–100. |
data-ba-step | 2 | How far one arrow-key press moves the handle. |
data-ba-label | — | Screen-reader name for the handle. |
data-ba-readout | — | A selector, e.g. #split. That element gets the live percentage. |
const slider = new BASlider('#hero-compare', { start: 30 }); slider.set(80); // move it yourself slider.destroy(); // unbind everything slider.root.addEventListener('ba:change', (e) => { console.log(e.detail.value); // 0–100, fires while dragging });