Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Stop animation from looping with jQuery

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: ""
    });
  });

});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 class="right-section">
  <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 class="right-section">
  <img />
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading