Mark Boulder
Mark Boulder

Reputation: 14277

Simple jQuery slideshow using animate()

Using jQuery's animate(), how do I slide each image once (with Slick.js-like CSS animations) and then stop at the last one?

<div class="slideshow" style="height: 100px; width: 200px; overflow: hidden;">
    <img src="http://lorempixel.com/200/100" />
    <img src="http://lorempixel.com/200/101" />
    <img src="http://lorempixel.com/200/102" />
</div>

This obviously won't work but:

var slide = $('.slideshow img'),
  delay = 500;

slide.each(function () {
    setTimeout(function () {
        $(this).animate({
            right: slide.width()
        });
    }, delay);
});

Here I'm using Slick, but I feel it's a bit overkill for what I'm trying to do:

http://jsfiddle.net/frank_o/eku4Lwt1/2/

$('.slideshow').slick({
    slide: 'img',
    autoplay: true,
    autoplaySpeed: 3000,
    accessibility: false,
    arrows: false,
    infinite: false,
    pauseonhover: false,
    responsive: false,
    swipe: false,
    touchmove: false,
}); 

Upvotes: 2

Views: 4511

Answers (2)

Henri Hietala
Henri Hietala

Reputation: 3041

You can (and should) do the actual animation with CSS. It is more efficient than jQuery animation since it's hardware accelerated.

JS:

changeSlide(1, $(".slideshow img"));
function changeSlide(i, items) {
    setTimeout(
      function() 
      {
          var currentItem = items.eq(i);
          var prevItem = items.eq(i-1);
          prevItem.css("left", -prevItem.width());
          currentItem.css("left", 0);
          if(i < items.size()-1)
              changeSlide(i+1, items);
      }, 3000);    
}

CSS:

.slideshow {
    position: relative;
}
.slideshow img {
    position: absolute;
    top: 0;
    left: -200px;
    width: 200px;
    height: 100px;
    -webkit-transition: all 0.6s ease;                  
    -moz-transition: all 0.6s ease;                 
    -o-transition: all 0.6s ease;   
    -ms-transition: all 0.6s ease;          
    transition: all 0.6s ease;
}
.slideshow img:first-child {
    left: 0px;
}

Notice that I started with index #1 because there's no need to animate the first image.

Here is a demo with JS & CSS: http://jsfiddle.net/eku4Lwt1/35/

Upvotes: 5

Ivan
Ivan

Reputation: 21

You can add a callback function after the slide change, add this function in settings and use it to stop the auto play.

onAfterChange: function() {
    if ($('.slideshow').slickCurrentSlide() == 2) {
        $('.slideshow').slickPause();
    }
}

You can check this online: http://jsfiddle.net/gq5L7wtw/

Upvotes: 1

Related Questions