Try out this simple JQ code snippet to achieve the desired effect
While it may not be the most optimal solution, it gets the job done. I included a background-color
for demonstration purposes, which can be removed leaving only the background-image
Check out the implementation on this JsFiddle link
This script creates two variables and assigns them to each image (before and after img) within div elements with the class name .somediv
An initial background-image
is added to the div
element
Upon hover, the background-image
of the div toggles between imgbefore
and imgafter
JQuery Code:
$(".somediv").each(function(){
var imgbef = $(this).data("imgbefore"),
imgaft = $(this).data("imgafter")
$(this).css({'background-image': 'url(' + imgbef + ')','background-color':'red'});
$(this).hover(function(){
$(this).css({'background-image': 'url(' + imgaft + ') ','background-color':'blue'});
}, function(){
$(this).css({'background-image': 'url(' + imgbef + ')','background-color':'red'});
});
});
HTML Structure:
<div class="somediv" data-imgbefore="img1.png" data-imgafter="img2.png"></div>
CSS Styling:
.somediv {
height:250px;
width:70%;
}
Feel free to reach out if you have any questions or need further assistance