Skip to content

Instantly share code, notes, and snippets.

@AmanDjenner
Created August 19, 2019 13:46
Show Gist options
  • Save AmanDjenner/3388ffc934f5d606495bbb22c6b70f09 to your computer and use it in GitHub Desktop.
Save AmanDjenner/3388ffc934f5d606495bbb22c6b70f09 to your computer and use it in GitHub Desktop.
Simple image comparison slider
<div class="section 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>
// Download this photo on Unsplash
// https://unsplash.com/@traf
$(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'
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
body {
background: #000;
height: 100vh;
width: 100%;
color: #fff;
margin: 0;
}
.section {
height: 100vh;
width: 100%;
}
.before {
background: url('https://tr.af/images/supply-urban-nyc-before.jpg') no-repeat center center;
background-size: cover;
}
.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;
}
.after {
background: url('https://tr.af/images/supply-urban-nyc-after.jpg') no-repeat center center;
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
background-size: cover;
position: relative;
display: block;
height: 100%;
width: auto;
}
@AmanDjenner
Copy link
Author

Simple image comparison slider
https://codepen.io/traf/pen/gOYMgoo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment