Image Slider Non working right

the code below dose not work right. I want an image slider that changes every 5 seconds, but if I hover over it it will stop and when i leave it starts again. When you click on it it will change. I can make it change every 5 seconds, and change it when i click, but i cant get it to stop when I hover.

$('document').ready(function() {

    var img = 0;
    var pic = ['nature', 'grass', 'earth', 'fall', 'fall2'];
    var slider = 'img.slide_img'; // html image

    function slide() {
        $(slider).attr('src', 'pictures/' + pic[img] + '.jpg');
        img++;
        if (img >= pic.length) {
            img = 0;
        }
    }

    $(slider).on('mouseleave', function() {
        auto(3000);
    });

    $(slider).on('click', function() {
        slide();
    });

    function auto(time) {
        setInterval(function() {
            slide();
        }, time)
    }   
});

Answer

There’s a bunch of problems:

  1. You don’t initialise your setInterval so that it only starts when triggering the mouseleave event.
  2. Every time the mouseleave event is triggered you start a new setInterval so you’ll probably end up having multiple running at the same time.
  3. Your desired behaviour is that hovering over the image will stop the slider, but you don’t have anything in place to do that.

How’s this: http://jsfiddle.net/BYossarian/uLAYB/

var img = 0,
    pic = ['nature', 'grass', 'earth', 'fall', 'fall2'],
    slider = $('img.slide_img'),
    timerID = 0,
    delay = 2000;

function slide() {
    slider.attr('src', 'http://placehold.it/200x200&text=' + pic[img]);
    img++;
    if (img >= pic.length) {
        img = 0;
    }
}

slider.on('mouseleave', function () {
    clearTimeout(timerID);
    auto();
});

slider.on('mouseenter', function () {
    clearTimeout(timerID);
});

slider.on('click', function () {
    clearTimeout(timerID);
    slide();
});

function auto() {
    timerID = setTimeout(function () {
        slide();
        auto();
    }, delay);
}

auto();

Notice I’m using ‘clearTimeout’ to prevent multiple timeouts running at the same time:

https://developer.mozilla.org/en-US/docs/Web/API/window.clearTimeout

Leave a Reply

Your email address will not be published. Required fields are marked *