user2598957
user2598957

Reputation: 263

jQuery animate left over time

I'm trying to make a div slide to the right by increasing the position left I want it to slowly go from the left hand side to the right and then loop back to the start. At the moment I'm just trying to animate the position so it doesn't jump instantly-

$('#pig').css('left', 200).animate(300);

Upvotes: 0

Views: 95

Answers (3)

adeneo
adeneo

Reputation: 318252

The syntax is

$('#pig').animate({left: 200}, 300);

jQuery.animate documentation

To add animations in a queue you can either just chain them

$('#pig').animate({left: 200}, 300).animate({left: 0}, 300);

FIDDLE

or use the callback argument, or use jQuery's queue to set up as many animations as you'd like in a queue

$('#pig').queue(function() {
    $(this).animate({left: 200}, 300);
    $(this).animate({left: 0}, 300);
}).dequeue();

FIDDLE

or to make it recursive, you can use a combination of both

(function ani() {
    $('#pig').queue(function() {
        $(this).animate({left: 200}, 300);
        $(this).animate({left: 0}, 300, ani);
    }).dequeue();
}());

FIDDLE

Upvotes: 5

Nanki
Nanki

Reputation: 828

Adeneo's answer is correct, but you also asked to loop back to the start. Assuming you want the div to go back to its original position, you need to chain another animation like this:

$('#pig').animate({left: 200}, 300, function() {
  $('#pig').animate({left: 0}, 300);
});

Upvotes: 1

sensorario
sensorario

Reputation: 21620

setTimeout(function () {
    $('#pig')
        .css('left', 200)
        .animate(300)
}, 1000)

Upvotes: 0

Related Questions