Skip to content

Instantly share code, notes, and snippets.

@edwardlorilla
Created May 2, 2021 11:44
Show Gist options
  • Save edwardlorilla/e89b7797e5b3e85e13a5ddc64aa16bf8 to your computer and use it in GitHub Desktop.
Save edwardlorilla/e89b7797e5b3e85e13a5ddc64aa16bf8 to your computer and use it in GitHub Desktop.
【JAVASCRIPT】picture comparison
<div class="div">
<div class="img1" style="background-image: url(https://picsum.photos/200/300);">
<div class="bar" data-flag="0"></div>
</div>
<div class="img2" style="background-image: url(https://picsum.photos/200/300);"></div>
</div>
$(document).ready(function(){
$(".bar").mousedown(function(){
$(this).parent().addClass("stop");
$(this).parent().next().addClass("stop");
$(this).attr("data-flag","1")
})
$(".div").mousemove(function(e){
var temp = $(this).find('.bar').attr("data-flag");
if(temp=="1"){
var w = $(this).width();
var x = e.offsetX;
var p = parseFloat((x/w).toFixed(2))*100;
$(this).children(".img1").css('width',p+'%');
$(this).children(".img2").css('left',p+'%');
}
})
$(document).mouseup(function(){
$(".img1,.img2").removeClass("stop");
$(".bar").attr("data-flag","0")
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
*{
margin: 0px;
padding: 0px;
user-select: none;
}
.div{
border: 1px solid lightgray;
width: 400px;
height: 200px;
margin: 10px;
float: left;
position: relative;
}
.img1{
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 50%;
}
.img2{
position: absolute;
top: 0;
bottom: 0;
left: 50%;
right: 0;
}
.img1,.img2{
background-position: center center;
background-size: 400px 200px;
background-repeat: no-repeat;
}
.img1{
background-position-x: 0;
}
.img2{
background-position-x: 100%;
filter: invert(100%);
}
.bar{
position: absolute;
top: 0;
bottom: 0;
right:-4px;
width: 8px;
background-color: gray;
cursor: ew-resize;
opacity: 0.2;
}
.stop{
pointer-events: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment