David
David

Reputation: 149

Image Carousel script stops after last image. Need it to repeat

I need my script to repeat after the last image is displayed. How can I go about resetting what the script has done then making it play again? The script changes the z-index of the current image. After the last image how can I make the script 'reset' the z-index of all the images and re-run from the top? Thanks!

<script>
function cycleImages(){
  var $active = $('#carousel .active');
  var $next = ($('#carousel .active').next().length > 0) ? $('#carousel .active').next() : $('#carousel img:first');
  $next.css('z-index',2);//move the next image up the pile
  $active.fadeOut(1500,function(){//fade out the top image
  $active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image
  $next.css('z-index',3).addClass('active');//make the next image the top one
  if ($('#carousel .active').next().length > 0) setTimeout('cycleImages()',1000);//check for a next image, and if one exists, call the function recursively
  });
}

$(document).ready(function(){
  // run every 7s
  setTimeout('cycleImages()', 1000);
})

</script>

Upvotes: 0

Views: 527

Answers (3)

Yogesh Khatri
Yogesh Khatri

Reputation: 1210

instead of bringing the next element to front, you can send the active element back by maintaning the counter for z-index, like

<script>
var zCount = 0;
function cycleImages(){
  var $active = $('#carousel .active');
  var $next = ($('#carousel .active').next().length > 0) ? $('#carousel .active').next() : $('#carousel img:first');

  $active.fadeOut(1500, function(){//fade out the top image
    $active.css('z-index', --zCount).show().removeClass('active'); //send the active image at the bottom of all images and unhide the image
    $next.addClass('active'); //make the next image as active
    setTimeout('cycleImages()',1000);
  });
}

$(document).ready(function(){
  setTimeout('cycleImages()', 1000);
})

</script>

Upvotes: 0

dreamweiver
dreamweiver

Reputation: 6002

Simple logic would be to check if the images have reached the end by comparing the .length with the total no of images (full length). if yes then go to first image i.e

('#carousel .active').first()

and call

setTimeout('cycleImages()',1000);

happy coding :)

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

You don't need to check again if there is a next .active element when setting a new Timeout

use just

setTimeout('cycleImages()',1000);

instead of

if ($('#carousel .active').next().length > 0) setTimeout('cycleImages()',1000);

Upvotes: 1

Related Questions