Background Image Comparison In jQuery

File Size: 1.31 KB
Views Total: 1011
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Background Image Comparison In jQuery

A jQuery script to create an image before/after effect that enables the visitor to compare two background images with cursor move.

How to use it:

1. Build the HTML for the image comparison slider.

<div class="before">
  <div class="section-wrapper">
    <div class="before-wrapper before">
      <div class="after-wrapper">
        <div class="after"></div>
      </div>
    </div>
    <div class="comparison-slider"></div>
  </div>
</div>

2. The necessary CSS for the image comparison wrappers.

.section-wrapper {
  position: relative;
  height: 100%;
  width: 100%;
}

.before-wrapper {
  position: relative;
  overflow: hidden;
  display: block;
  height: 100%;
  width: auto;
}

.before-wrapper:before {
  display: block;
  height: 100%;
  width: 100%;
  content: '';
}

.after-wrapper {
  -webkit-transform: translateX(50%);
  transform: translateX(50%);
  position: absolute;
  overflow: hidden;
  bottom: 0;
  right: 0;
  left: 0;
  top: 0;
}

3. Add before/after background images.

.before {
  background: url('before.jpg') no-repeat center center;
  background-size: cover;
}

.after {
  background: url('after.jpg') no-repeat center center;
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
  background-size: cover;
  position: relative;
  display: block;
  height: 100%;
  width: auto;
}

4. Include the necessary jQuery library at the end of the document.

<script src="/path/to/jquery.min.js"></script>

5. The jQuery script to activate the image comparison effect.

$(function(){
  $('.before-wrapper').on("mousemove", function (e) {
    var offsets = $(this).offset();
    var fullWidth = $(this).width();
    var mouseX = e.pageX - offsets.left;
    if (mouseX < 0) { mouseX = 0; }
    else if (mouseX > fullWidth) { mouseX = fullWidth }
    $(this).parent().find('.comparison-slider').css({ left: mouseX, transition: 'none' });
    $(this).find('.after-wrapper').css({ transform: 'translateX(' + (mouseX) + 'px)', transition: 'none' });
    $(this).find('.after').css({ transform: 'translateX(' + (-1 * mouseX) + 'px)', transition: 'none' });
  });
  $('.section-wrapper').on("mouseleave", function () {
    $(this).parent().find('.comparison-slider').css({
      left: '50%', transition: 'all .3s'
    });
    $(this).find('.after-wrapper').css({
      transform: 'translateX(50%)', transition: 'all .3s'
    });
    $(this).find('.after').css({
      transform: 'translateX(-50%)', transition: 'all .3s'
    });
  });
});

This awesome jQuery plugin is developed by Traf. For more Advanced Usages, please check the demo page or visit the official website.