0

So I'm making this slideshow on my website. Right now it moves all pictures outside the screen to the left, appends the first item to the end of the container and then repeats. The thing is I had to set a timer bigger than the animation time or else it would every other time animate the wrong element. How can I make it repeat when the appendTo function is complete without having a delay?

What it looks like: https://gyazo.com/04b427117ee9d01f65fcdba790ec0730

Javascript:

$(function(){
setInterval(function(){
    var p = $(".photo-grid-slideshow .photo-crop").css('width');
    $(".photo-grid-slideshow .photo-crop:first-of-type").animate({marginLeft: '-=' + p}, 3000, "linear", function(){
        $(this).css("margin-left", 0).appendTo('.photo-grid-slideshow');
    })
}, 3500);
});
1
  • You should add the working code snippet here or on jsfiddle.net. Commented Feb 1, 2016 at 17:10

2 Answers 2

2

Just run it again after your .appendTo:

$(function(){
  function animate(){
      var p = $(".photo-grid-slideshow .photo-crop").css('width');
      $(".photo-grid-slideshow .photo-crop:first-of-type").animate({marginLeft: '-=' + p}, 3000, "linear", function(){
        $(this).css("margin-left", 0).appendTo('.photo-grid-slideshow');
        animate(); // here we call it again
    })
  }
  animate(); // start animation
})
Sign up to request clarification or add additional context in comments.

2 Comments

If you go down this route, you just need to make sure that the element exists before trying to animate it var $elem = $(".photo-grid-slideshow .photo-crop:first-of-type"); if($elem.length){ $elem.animate(...
Thank you! Works like a charm :)
1

For an use case like this where you want to chain animations, using a library like GreenSock could be really helpful. An added benefit is that the animations will be much smoother and more customizable than using jQuery's native animate functionality.

As for your current implementation, it would be easier to provide help if you included a snippet of the HTML and CSS that goes along with your script.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.