Reputation: 85653
I've the following jquery code:
$('#swipe').on('click',function(){
$('.swipe-1').animate({width:'100%'},1000);
$('.swipe-2').delay(1000).animate({width:'100%'},1000);
$('.swipe-3').delay(2000).animate({width:'100%'},1000);
$('.swipe-4').delay(3000).animate({width:'100%'},1000);
$('.swipe-5').delay(4000).animate({width:'100%'},1000);
$('.swipe-6').delay(5000).animate({width:'100%'},1000);
$('.swipe-7').delay(6000).animate({width:'100%'},1000);
});
Can I shorten my above code?
Upvotes: 0
Views: 50
Reputation: 40639
You can use a common class like swipe
instead of making 7 different classes:
$('#swipe').on('click',function(){
$('.swipe').each(function(i,v){
$(this).delay(i*1000).animate({width:'100%'},1000);
});
});
delay() may not work here because there is no queue
of animation, so setTimeout
is better to use like,
$('#swipe').on('click',function(){
$('.swipe').each(function(i,v){
var $this=$(this);
setTimeout(function(){
$this.animate({width:'100%'},1000);
},(i*1000));
});
});
Upvotes: 3
Reputation: 85653
Like this ?
$('#swipe').on('click',function(){
for(var i=0;i<7;i++){
$('.swipe-'+(i+1)).delay(i*1000).animate({width:'100%'},1000);
}
});
Upvotes: 2