Reputation: 9713
I wanted to make my own slideshow using jQuery. Here I got stuck with the direction of the slider image. I want it to loop only one direction ( right to left ). Please see my code Below:
HTML:
<div class="flash-banner">
<ul>
<li>
<img src="img/flash-banner.jpg" alt="Black glass banner " />
</li>
<li>
<img src="img/flash-banner-contact.jpg" alt="Black glass banner " />
</li>
<li>
<img src="img/flash-banner-our-work.jpg" alt="Black glass banner " />
</li>
</ul>
</div>
JavaScript:
$(document).ready( function ( e ) {
slideshow( 6000 );
});
function slideshow( speed ) {
// Get width from image
$pic = $('.flash-banner ul li img')[0];
$width = $pic.width;
// Count the total number of children of UL
$count = $('.flash-banner ul').children().length;
// Set width to UL
var $ul = $width * $count;
$('.flash-banner ul').css('width', $ul);
var i = 1;
setInterval( function ( e ) {
if ( i > $count - 1 ) {
// I think the problem is here, but I can't fix it
i = 0;
var b = 0;
} else {
var b = $width * i;
}
console.log( b );
$element = $('.flash-banner ul');
$element.animate(
{'margin-left': -b },
{ duration: speed },
{ delay: speed }
);
i++;
}, speed );
}
I also made a demo at http://jsfiddle.net/FzDtD/1/
Upvotes: 0
Views: 1327
Reputation: 35533
Use clearInterval()
to stop the animation instead of resetting i
to 0.
If you want to reloop the animation, call .stop()
to stop it, fix the css to move the banner back to the original position and call the animation function again.
Alternatively, you can try just stopping the animation and resetting all values to the initial state, but I find that can get messy sometimes since you need to manually ensure that you reset all variables for this to work right.
Upvotes: 1