ivailo ivailo - 3 months ago 20
jQuery Question

Jqerry slider on click

Hey guys I want to make this slider do it's work when you click the slider. how can I do this? This is the code: http://jsfiddle.net/EjZzs/15/

$(function() {

//settings for slider
var width = 720;
var animationSpeed = 1000;
var pause = 3000;
var currentSlide = 1;

//cache DOM elements
var $slider = $('#slider');
var $slideContainer = $('.slides', $slider);
var $slides = $('.slide', $slider);

var interval;

function startSlider() {
interval = setInterval(function() {
$slideContainer.animate({'margin-left': '-='+width}, animationSpeed, function() {
if (++currentSlide === $slides.length) {
currentSlide = 1;
$slideContainer.css('margin-left', 0);
}
});
}, pause);
}
function pauseSlider() {
clearInterval(interval);
}

$slideContainer
.on('mouseenter', pauseSlider)
.on('mouseleave', startSlider);

startSlider();


});

Answer

Move the code that does the sliding to its own function, and call that from the setInterval and on a click:

  function startSlider() {
    interval = setInterval(slide, pause);
  }

  function slide() {
    $slideContainer.animate({
      'margin-left': '-=' + width
    }, animationSpeed, function() {
      if (++currentSlide === $slides.length) {
        currentSlide = 1;
        $slideContainer.css('margin-left', 0);
      }
    });
  }

  $slideContainer
    .on('mouseenter', pauseSlider)
    .on('mouseleave', startSlider)
    .on('click', slide);

http://jsfiddle.net/uctr94ve/

Comments