MullerA
MullerA

Reputation: 387

How to make mouseenter function loop

I would like to make a function where if the user hovers his cursor over an image, the image changes and cycles through a bunch of images I've designated. I've achieved this previously, but instead of on hover, I used on click which is fairly easier.

In short how do I make the images cycle on mouseenter?

My code:

var n = 0;

var images = ["3.jpeg","4.jpeg","6.jpeg","7.jpeg","8.jpeg","10.jpeg","12.jpeg","13.jpeg","14.jpeg","15.jpeg","16.jpeg"];

var image = $('#himg');

image.on('mouseenter', function change() {

    var newN = n+1;

    if (newN >= images.length) { newN = 0 };

    image.attr('src', images[n]);

    image.fadeOut(200, function () {
        image.attr('src', images[newN]);
        image.fadeIn();
        n = newN;
    });
});

Upvotes: 0

Views: 375

Answers (1)

intentionally-left-nil
intentionally-left-nil

Reputation: 8304

mouseenter only fires once, when the mouse moves into the range of the dom element. When the mouse finally leaves, a mouseleave event is fired. You can use this to start an interval to cycle through your images.

var n = 0;

var images = ["3.jpeg","4.jpeg","6.jpeg","7.jpeg","8.jpeg","10.jpeg","12.jpeg","13.jpeg","14.jpeg","15.jpeg","16.jpeg"];

var image = $('#himg');

var intervalId;
var intervalTimeout = 200;

image.on('mouseenter', function change() {
    intervalId = setInterval(function() {
      var newN = n+1;

      if (newN >= images.length) { newN = 0 };

      image.attr('src', images[n]);

      image.fadeOut(200, function () {
          image.attr('src', images[newN]);
          image.fadeIn();
          n = newN;
      });
    }, intervalTimeout);
});

image.on('mouseleave', function() {
  clearInterval(intervalId);
});

Upvotes: 1

Related Questions