← Volver

Before / After Comparison Slider

Interactive before-after image comparison with draggable slider

Marketing
Preview
<section class="w-full max-w-4xl mx-auto py-16 px-6">

  <div class="relative overflow-hidden rounded-2xl border">

    <!-- Before -->
    <img src="https://images.unsplash.com/photo-1500530855697-b586d89ba3ee?q=80&w=1200&auto=format&fit=crop"
         class="w-full h-[400px] object-cover">

    <!-- After -->
    <div id="after" class="absolute inset-0 overflow-hidden" style="width:50%">
      <img src="https://images.unsplash.com/photo-1492724441997-5dc865305da7?q=80&w=1200&auto=format&fit=crop"
           class="w-full h-[400px] object-cover">
    </div>

    <!-- Slider -->
    <div id="slider"
         class="absolute top-0 bottom-0 left-1/2 w-1 bg-white cursor-ew-resize">
      <div class="absolute top-1/2 -translate-y-1/2 -left-3 w-6 h-6 bg-white rounded-full shadow"></div>
    </div>

  </div>

  <script>
    const slider = document.getElementById("slider");
    const after = document.getElementById("after");
    const container = slider.parentElement;

    let isDragging = false;

    slider.addEventListener("mousedown", () => isDragging = true);
    window.addEventListener("mouseup", () => isDragging = false);

    window.addEventListener("mousemove", (e) => {
      if (!isDragging) return;

      const rect = container.getBoundingClientRect();
      let x = e.clientX - rect.left;
      x = Math.max(0, Math.min(x, rect.width));

      slider.style.left = x + "px";
      after.style.width = x + "px";
    });
  </script>

</section>