Smooth Touch-enabled Image Comparison Slider In JavaScript

Category: Image , Javascript | March 8, 2023
Authormaxulyanov
Last UpdateMarch 8, 2023
LicenseMIT
Views441 views
Smooth Touch-enabled Image Comparison Slider In JavaScript

A smooth and mobile-friendly image comparison slider that allows the user to compare two images by sliding a vertical bar, revealing different parts of each image.

How to use it:

1. Create an HTML container for your image comparison slider, and add two images to it. These images should be the same size and aspect ratio and should represent the “before” and “after” versions of your comparison.

<div class="js-comparison-container">
  <img class="comparison-image" src="before.jpg" alt="">
  <img class="comparison-image" src="after.jpg" alt="">
</div>

2. Load the ImageComparison.css and ImageComparison.js files in the document.

<link rel="stylesheet" href="src/ImageComparison.css" />
<script src="src/ImageComparison.js"></script>

3. Initialize the image comparison slider. Done.

var imageContainer = document.querySelectorAll('.js-comparison-container');
var images = imageContainer.querySelectorAll('.comparison-image');
new ImageComparison({
    container: imageContainer,
    startPosition: 70, // 70%
    data: [
      {
        image: images[0],
        label: 'before'
      },
      {
        image: images[1],
        label: 'after'
      }
    ],
});

You Might Be Interested In:


Leave a Reply