Interactive Diagonal Image Comparison With JavaScript

Category: Image , Javascript | November 22, 2017
Author:bmccaffray
Views Total:1,705 views
Official Page:Go to website
Last Update:November 22, 2017
License:MIT

Preview:

Interactive Diagonal Image Comparison With JavaScript

Description:

This is a small script to create a fancy diagonal slider that allows to compare two different images with mouse move.

How to use it:

Create the html.

<div class='comparison-wrapper' id='comparison-wrapper'>
  <div class='comparison design'>
    <div class='comparison-content'>
      <img src='before.jpg'>
    </div>
  </div>
  <div class='comparison dev'>
    <div class='comparison-content'>
      <img src='after.jpg'>
    </div>
  </div>
</div>

The core CSS/CSS3 styles.

body .comparison-wrapper {
  position: relative;
  width: 100%;
  height: 400px;
  overflow: hidden;
}
body .comparison {
  position: absolute;
  overflow: hidden;
}
body .comparison.dev {
  transform: skew(-30deg);
  margin-left: -500px;
  width: calc(50vw + 500px);
}
body .comparison.dev .comparison-content {
  transform: skew(30deg);
  margin-left: 500px;
}
body .comparison .comparison-content { height: 400px; }
body .comparison img { width: 100vw; }

The main JavaScript to activate the image comparison slider.

document.addEventListener('DOMContentLoaded', function(){
  let comparison = document.getElementById('comparison-wrapper');
  let devLayer = comparison.querySelector('.dev');
  let delta = 0;
  comparison.addEventListener('mousemove', function(e){
      delta = (e.clientX - window.innerWidth / 2) * 0.5;
      devLayer.style.width = e.clientX + 500 + delta + 'px';
  });
})

You Might Be Interested In:


Leave a Reply