In this tutorial, we are going to see how to flip an image using jQuery and CSS. In a previous tutorial, we have seen various jQuery animation to rotate image.
In this example, we are flipping images in a horizontal direction using a 3D transform. We are using the CSS transform property to flip images in X-axis. This CSS property will be set via jQuery.
This code shows HTML markup for the flippable image.
<div id="flip-box">
<img src="fixed_bg.jpg">
</div>
<div id="flip-link" class="demo-submit">
Flip the Image
</div>
and the styles are,
<style>
#flip-box {
width: 200px;
height: 150px;
transition: 0.9s;
transform-style: preserve-3d;
position: relative;
}
.demo-submit{
padding: 10px 20px;
background: #555;
border: 0;
color: #FFF;
display:inline-block;
margin-top:20px;
}
</style>
This jQuery script shows how to change the image transform property on the click event. By changing transform property the image will flip back and forth. The code is,
<script type="text/javascript">
$("#flip-link").on("click",function(){
if($("#flip-box").css("transform") == 'none') {
$("#flip-box").css("transform","rotateY(180deg)");
$("#flip-box img").attr("src","fixed_bg1.jpg");
}
else {
$("#flip-box").css("transform","");
$("#flip-box img").attr("src","fixed_bg.jpg");
}
})
</script>