Reputation: 15293
I am doing an animation for which I need to move my div by 25px. Once the div reached 25px it should flip back to 0px, it should not stop any way. For that, I need a function to loop the div. This is what I have so far:
var x = 0;
var condition = true;
var loopIt = function (){
while(x < 25 && condition == true){
x++;
console.log(x);
if(x == 25){
condition = false;
}
}
while(x > 0 && condition == false){
x--;
if(x == 0){
condition = true;
}
console.log(x);
}
setTimeout(loopIt, 1000);
}
loopIt();
It is working good, but i feel this is ugly. Is there any shorter way to archive the same?
Upvotes: 0
Views: 585
Reputation: 4520
Fiddle Demo: http://jsfiddle.net/EPmLU/1/
function animateDiv() {
$('div').animate({
left: '+=25' // animate left 25
}, 1000, function () {
$('div').css('left', '-=25'); // reset animated div to orig position
animateDiv();
});
}
animateDiv();
Upvotes: 0
Reputation: 2458
How about something like this:
function endless(){
$("#div").animate({
left:'+=25px',
}, 500, function() {
$("#div").animate({
left:'-=25px',
}, 500, function() {
endless();
});
});
};
endless();
And here the jsfiddle: http://jsfiddle.net/79y2j/
Upvotes: 1