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>
Look in your browser console.
animatethisdoes not return anything, which means that the lineis always going to crash (something like “TypeError: Cannot call method ‘stop’ of undefined”). You’re also mixing up the order of the animations in the
completecallback.Stop, breathe, and think about what your code above is actually doing.
Okay, so after the
marginLeftis increased, you want to decrease it. Then you want to start all over. Right? So:There are lots of other ways to skin this cat, but this does work. http://jsfiddle.net/mattball/rKu6Y/