Categories We Write About

Build an image comparison tool

Here’s a basic implementation of an Image Comparison Tool using HTML, CSS, and JavaScript. This tool allows you to compare two images using a slider that reveals one image over another.

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <title>Image Comparison Tool</title> <style> * { box-sizing: border-box; } body { margin: 0; font-family: Arial, sans-serif; background: #f4f4f4; display: flex; justify-content: center; align-items: center; height: 100vh; } .container { position: relative; width: 700px; max-width: 100%; overflow: hidden; box-shadow: 0 5px 15px rgba(0,0,0,0.2); } .img-wrapper { position: relative; width: 100%; } .img-wrapper img { width: 100%; display: block; } .overlay { position: absolute; top: 0; left: 0; overflow: hidden; width: 50%; } .slider { position: absolute; top: 0; left: 50%; width: 4px; height: 100%; background: #fff; cursor: ew-resize; z-index: 10; } .slider::before { content: ''; position: absolute; top: 50%; left: -8px; width: 20px; height: 20px; background: #007BFF; border-radius: 50%; transform: translateY(-50%); box-shadow: 0 2px 6px rgba(0,0,0,0.3); } </style> </head> <body> <div class="container" id="compareContainer"> <div class="img-wrapper"> <img src="image1.jpg" alt="Image 1"> <div class="overlay" id="imgOverlay"> <img src="image2.jpg" alt="Image 2"> </div> <div class="slider" id="slider"></div> </div> </div> <script> const container = document.getElementById('compareContainer'); const slider = document.getElementById('slider'); const overlay = document.getElementById('imgOverlay'); let isDown = false; slider.addEventListener('mousedown', () => isDown = true); slider.addEventListener('touchstart', () => isDown = true); window.addEventListener('mouseup', () => isDown = false); window.addEventListener('touchend', () => isDown = false); window.addEventListener('mousemove', drag); window.addEventListener('touchmove', drag); function drag(e) { if (!isDown) return; const rect = container.getBoundingClientRect(); const x = e.touches ? e.touches[0].clientX : e.clientX; let position = x - rect.left; if (position < 0) position = 0; if (position > rect.width) position = rect.width; overlay.style.width = position + 'px'; slider.style.left = position + 'px'; } </script> </body> </html>

How to Use:

  • Replace image1.jpg and image2.jpg with paths to your own images.

  • Open the HTML file in a browser to interact with the comparison slider.

Let me know if you need this in a React or Vue component, or want features like zoom, annotation, or mobile responsiveness.

Share This Page:

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories We Write About