Reputation: 1501
So I want to convert this code:
$('.spawn_worm').animate({
left: '+=20px',
top: '-=20px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '-=16px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '-=12px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '-=8px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '-=4px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '+=0px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '+=4px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '+=8px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '+=8px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '+=12px'
},100, "linear", function(){
$('.spawn_worm').animate({
left: '+=20px',
top: '+=16px'
},100, "linear", function(){
});
});
});
});
});
});
});
});
});
});
});
To something less stupid. Because it's gonna take me like 1 year to finish that and because it's a lot of code I think it can be solved with a loop.
I want the animate function property left
to be always the same +=20px
. And the property top
to start in -20px
and increase to 180px
, then decrease again to 180px
and finish after (window.width)/20
loops.
Is this even posible? Thank you and sorry for the noob question (:
Upvotes: 1
Views: 54
Reputation: 15846
You can use something like this. Change the if condition as per your need.
var count = parseInt(window.innerWidth/20);
function animateElement(){
if(count){
$('.spawn_worm').animate({
left: '+=20px',
top: '-=20px'
}, 100, animateElement);
count--;
}
}
animateElement();
Upvotes: 1
Reputation: 388316
You can use a looping like
jQuery(function($) {
$('button').click(function() {
var top = 20,
sign = -1;
anim();
function anim() {
$('.spawn_worm').animate({
left: '+=20px',
top: (sign == 1 ? '+' : '-') + '=' + top + 'px'
}, 100, "linear", function() {
if (sign * top < 16) {
top += 2 * sign;
if (!top) {
sign = 1;
}
anim();
}
});
}
});
});
body {
height: 1000px;
margin-top: 200px;
}
.ct {
position: relative;
height: 500px;
}
.spawn_worm {
height: 50px;
position: absolute;
background-color: red;
display: inline-block;
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Test</button>
<div class="ct">
<div class="spawn_worm"></div>
</div>
Upvotes: 0