Pause jQuery on hover

I just want to be able to pause animation on hover. I am trying to find a good way to do this, but there were some problems. I tested some hover / stop functions, but I cannot get them to work correctly.

jQuery(document).ready(function() {
  setInterval(function() {
    jQuery('#testimonials .slide').filter(':visible').fadeOut(1000, function() {
      if (jQuery(this).next('.slide').size()) {
        jQuery(this).next().fadeIn(1000);
      } else {
        jQuery('#testimonials .slide').eq(0).fadeIn(1000);
      }
    });
  }, 5000);
});
#quote {
  width: 100%;
  height: 130px;
  background-position: center bottom;
  background-repeat: no-repeat;
  margin-bottom: 65px;
  overflow: hidden;
}

#testimonials .slide {
  color: #555555;
}

#testimonials .testimonial-quote {
  display: inline;
  width: 600px;
  height: 170px;
  margin: 0;
  padding: 0;
  float: left;
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quote">
  <div id="testimonials">
    <div class="slide">
      <div class="testimonial-quote">
        <p>Text 1</p>
        <h4 class="title">Title 1</h4>
      </div>
    </div>
  </div>
</div>
Run code
+4
source share
1 answer

You can achieve this by invoking clearInterval()when the slide freezes, and then re-create the interval when the mouse leaves the slide, something like this:

jQuery(document).ready(function($) {
  var $slides = $('#testimonials .slide');
  
  function beginSlideInterval() {
    return setInterval(function() {
      $slides.filter(':visible').fadeOut(1000, function() {
        var $next = $(this).next().length ? $(this).next() : $slides.first();
        $next.fadeIn(1000);
      });
    }, 3000);
  }
 
  var slideInterval = beginSlideInterval();
  
  $slides.on('mouseenter', function() {
    clearInterval(slideInterval);
  }).on('mouseleave', function() {
    slideInterval = beginSlideInterval();
  });
});
#quote {
  width: 100%;
  height: 130px;
  background-position: center bottom;
  background-repeat: no-repeat;
  margin-bottom: 65px;
  overflow: hidden;
}

#testimonials .slide {
  color: #555555;
}

#testimonials .testimonial-quote {
  display: inline;
  width: 600px;
  height: 170px;
  margin: 0;
  padding: 0;
  float: left;
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quote">
  <div id="testimonials">
    <div class="slide">
      <div class="testimonial-quote">
        <p>Text 1</p>
        <h4 class="title">Title 1</h4>
      </div>
    </div>
  </div>
</div>
Run code

Please note that I reduced the interval to make the effect more obvious.

+3
source

Source: https://habr.com/ru/post/1687038/


All Articles