Normally when animating an object with jQuery, the animation is added to the queue for that object. When previous animations have ended, the animation starts running. Your code above does exactly that, animates horizontally, then vertically.
This behavior can be overwritten by the use of the queue option of the animation (set it to false).
function loop_horiz(direction) {
var d = (direction == 1) ? '+' : '-';
$('.op').animate({
left: d + '200'
}, {
queue: false,
duration: 4000,
done: function () {
loop_horiz(direction * (-1))
}
});
}
function loop_vert(direction) {
var d = (direction == 1) ? '+' : '-';
$('.op').animate({
bottom: d + '200'
}, {
queue: false,
duration: 2000,
done: function () {
loop_vert(direction * (-1))
}
});
}
loop_horiz(1);
loop_vert(1)
Another (uglier) possibility is to merge the animations, but it would require you to split the horizontal animation in two for half the distance running over 2s.
http://api.jquery.com/animate/
Even better, with queue as string you can add the animations to different queues.
Same code as above, but using different queues for vertical and horizontal animation:
function loop_horiz(direction) {
var d = (direction == 1) ? '+' : '-';
$('.op').animate({
left: d + '200'
}, {
queue: 'horizontal',
duration: 4000,
done: function () {
loop_horiz(direction * (-1))
}
}).dequeue('horizontal');
}
function loop_vert(direction) {
var d = (direction == 1) ? '+' : '-';
$('.op').animate({
bottom: d + '200'
}, {
queue: 'vertical',
duration: 2000,
done: function () {
loop_vert(direction * (-1))
}
}).dequeue('vertical');
}
loop_horiz(1);
loop_vert(1)
DEMO: http://jsfiddle.net/Uewzc/1/
queue: false, the animations won't loop