What I want to happen is when I hover the cursor to an image, it will start the looping animation. And when I leave the cursor, it stops the animation. It indeed stops but the looping animation does not work anymore when I hover it to a image again.
$(".right-section img").mouseenter(function() {
var hoveredImage = $(this).attr("id");
function loop() {
$("#" hoveredImage).animate({
bottom: "15px"
}, 500).animate({
bottom: 0
}, 500, function() {
loop();
});
}
loop();
$("#" hoveredImage).mouseleave(function() {
$(this).dequeue();
$(this).css({
bottom: ""
});
});
});
CodePudding user response:
To do what you require call stop()
to clear the animation queue for the img
:
$(".right-section img").mouseenter(function() {
function loop($img) {
$img.animate({
bottom: "15px"
}, 500).animate({
bottom: 0
}, 500, function() {
loop($img);
});
}
loop($(this));
}).mouseleave(function() {
$(this).stop(true);
});
.right-section img {
width: 100px;
height: 100px;
display: block;
background-color: #C00;
position: absolute;
bottom: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div >
<img />
</div>
That being said, a far better approach would be to use CSS for the animation. CSS performs better, and also it better meets the separation of concerns principle. Try this:
.right-section img {
width: 100px;
height: 100px;
display: block;
background-color: #C00;
position: absolute;
bottom: 0;
}
.right-section img:hover {
animation: bounce 1s ease-in-out infinite;
}
@keyframes bounce {
0% { bottom: 0; }
50% { bottom: 15px; }
100% { bottom: 0; }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div >
<img />
</div>