Alex Rivera | Logout

How do I use jquery's animate method to make a div move back and forth

Asked 2012-02-25T08:05:04.047
10

I want to make a div animate horizontally back and forth within a certain area. The problem I have right now is that I can't figure out how to make my div move back after it has moved forward.

Here is the script that I am using:

  <script type="text/javascript">
    var animatethis = function (targetElement, speed) {
        $(targetElement).animate(
            {
                marginLeft: "+=250px"
            },
            {
                duration: speed,
                complete: function () {
                    animatethis(this, speed);
                    animatethis.stop();
                    $(targetElement).animate({ marginLeft: "-=250px" });
                }
            }
                    )
    };
    animatethis($('#q1'), 5000);
</script> 
Edit
Report

2 Answers

8

Are you trying to do this? http://jsfiddle.net/vwH6R/2/

setInterval(function(){
    $("div").stop(true,true).animate({left: 300}, 1000, 
          function(){ $(this).stop(true,true).animate({left: 0}, 1000); 
    });
}, 2000);​
answered 2012-02-25T08:16:40.143
0

Use jQuery queue() method to chain events : http://api.jquery.com/queue/

answered 2012-02-25T08:10:36.627

Your Answer