Tim Sadvak
Tim Sadvak

Reputation: 101

On mouseout stop setInterval

I'm trying to create a simple image rotator on hover effect. It working properly on mouse hover, but doesn't work when mouse out method.

var imgFlip = $("img").data( "flip" );
var imgOriginal = $("img").data( "original" );
var images = imgFlip.split(/,|, |;|; /);
var index = 0;

function rotateImage()
{
  $('.img-rotator').fadeOut('fast', function() 
  {
    $(this).attr('src', images[index]);

    $(this).fadeIn('fast', function() 
    {
      if (index == images.length-1)
      {
        index = 0;
      }
      else
      {
        index++;
      }
    });
  });
} 

$(document).ready(function()
{
  $('.img-rotator') 
    .mouseover(function () {
      var refreshIntervalId = setInterval (rotateImage, 1000);
    })
    .mouseout(function () {
        $(this).attr('src', imgOriginal);
   })
});

Jsfiddle example here - https://jsfiddle.net/wbz35L68/15/ Thank you for any advice

Upvotes: 0

Views: 506

Answers (1)

dysfunc
dysfunc

Reputation: 2008

You need to clear the setInterval on mouseout. I also reworked some of your code to clean things up and cache refs. You should also use mouseenter and mouseleave for this.

$(document).ready(function(){
  // cache selector
  var rotator = $('.img-rotator'),
      // grab all data
      data = rotator.data(),
      // ref flip
      imgFlip = data.flip,
      // ref original
      imgOriginal = data.original,
      // get image urls
      images = imgFlip.split(/,|, |;|; /),
      // start index
      index = 0,
      // ref interval
      refreshIntervalId = null;

  function rotateImage(){
    rotator.fadeOut('fast', function(){
      $(this)
        .attr('src', images[index])
        .fadeIn('fast', function(){
          var last = index === images.length - 1;
          
          index = last ? 0 : index + 1; 
      });
    });
  } 

  rotator
    .mouseenter(function(){
      refreshIntervalId = setInterval(rotateImage, 1000);
    })
    .mouseleave(function(){
      // clear interval and set null
      clearInterval(refreshIntervalId) && (refreshIntervalId = null); 
      
      $(this).attr('src', imgOriginal);
   })
});
.container {
  margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="row">
    <div class="col">
      <img class="img-rotator" data-flip="http://www.snorkl.tv/dev/loaderMax/images/bird.png, http://www.snorkl.tv/dev/loaderMax/images/whale.png" data-original="http://www.snorkl.tv/dev/loaderMax/images/crab.png" src="http://www.snorkl.tv/dev/loaderMax/images/crab.png" width="320" height="200"/>
    </div>
  </div>
</div>

Upvotes: 3

Related Questions