I am aiming to create a unique image effect using jQuery's animate API. This effect involves swapping the image source, fading in/out, and applying a rotateY animation. However, there seems to be an issue where the animation triggers multiple times if the mouse cursor is dragged several times before the mouseenter animation finishes.
The provided code snippet:
$(document).ready(function() {
$("img[data-alt-src]")
.mouseenter(function() {
var img = $(this);
img.finish().animate({ opacity: '-=1.0', deg: '+=90' }, {
duration: 250,
step: function(now) {
img.css({
'-moz-transform': 'rotateY('+now+'deg)',
'-webkit-transform': 'rotateY('+now+'deg)',
'-o-transform': 'rotateY('+now+'deg)',
'-ms-transform': 'rotateY('+now+'deg)',
transform: 'rotateY('+now+'deg)'
});
},
complete: function() {
img.data('tmp-src', img.attr('src'));
img.attr('src', img.data('alt-src'));
}
});
// Additional animation logic
})
.mouseleave(function() {
var img = $(this);
img.finish().animate({ opacity: '-=1.0', deg: '+=90' }, {
duration: 250,
step: function(now) {
img.css({
'-moz-transform': 'rotateY('+now+'deg)',
'-webkit-transform': 'rotateY('+now+'deg)',
'-o-transform': 'rotateY('+now+'deg)',
'-ms-transform': 'rotateY('+now+'deg)',
transform: 'rotateY('+now+'deg)'
});
},
complete: function() {
img.attr('src', img.data('tmp-src'));
}
});
// Additional animation logic
});
});
img {
width: 150px;
height: 150px;
margin-right: 1.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div style="position: relative; display: inline-block">
<img
src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_1-270x270.jpg"
data-alt-src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_3-270x270.jpg"
alt="">
<img
src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_1-270x270.jpg"
data-alt-src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_3-270x270.jpg"
alt="">
<img
src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_1-270x270.jpg"
data-alt-src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_3-270x270.jpg"
alt="">
<img
src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_1-270x270.jpg"
data-alt-src="http://mcenter.lazim.org/image/cache/catalog/demo/nikon_d300_3-270x270.jpg"
alt="">
</div>
</body>
</html>