simple before-after slider

by Stalk

HTML

<div id="block1">
  <div id="block2">
    <div id="mover"></div>
  </div>
</div>

CSS

#block1 {
  width: 500px;
  height: 300px;
  background: url(https://picsum.photos/500/300);
  position: relative;
}

#block2 {
  width: 250px;
  height: 300px;
  background: url(https://picsum.photos/500/301);
  background-position: top right;
  overflow: hidden;
  position: absolute;
  right: 0;
}

#mover {
  width: 10px;
  height: 100%;
  background: orange;
  position: absolute;
  cursor: col-resize;
  left: -5px;
  top: 0;
}

JavaScript

console.clear();
let resizeFlag = false;
document.addEventListener('mouseup', stopResize);
mover.addEventListener('mousedown', startResize);
block1.addEventListener('mousemove', resize);

function startResize() {
  resizeFlag = true;
  document.body.style.cursor = 'col-resize';
}

function stopResize() {
  resizeFlag = false;
  document.body.style.cursor = '';
}

function resize(evt) {
  if (!resizeFlag) return;
  const rect = block1.getBoundingClientRect();
  const x = evt.clientX - rect.left;
  const newWidth = block1.clientWidth - x;
  block2.style.width = newWidth + 'px';
}