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>
The jQuery animate() method is used to create custom animations. Syntax: $(selector). animate({params},speed,callback);
The animate() method performs a custom animation of a set of CSS properties. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect. Only numeric values can be animated (like "margin:30px").
Easing out causes the animation to start more quickly than linear ones, and it also has deceleration at the end. Easing out is typically the best for user interface work, because the fast start gives your animations a feeling of responsiveness, while still allowing for a natural slowdown at the end.
The solution to Jquery To Animate A Flash To The Button Selected will be demonstrated using examples in this article. $("#someElement"). fadeOut(100). fadeIn(100).
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);
Look in your browser console. animatethis
does not return anything, which means that the line
animatethis.stop();
is 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 complete
callback.
Stop, breathe, and think about what your code above is actually doing.
Okay, so after the marginLeft
is increased, you want to decrease it. Then you want to start all over. Right? So:
function animatethis(targetElement, speed) {
$(targetElement).animate({ marginLeft: "+=250px"},
{
duration: speed,
complete: function ()
{
targetElement.animate({ marginLeft: "-=250px" },
{
duration: speed,
complete: function ()
{
animatethis(targetElement, speed);
}
});
}
});
};
animatethis($('#q1'), 5000);
There are lots of other ways to skin this cat, but this does work. http://jsfiddle.net/mattball/rKu6Y/
Try this fiddle
HTML
<div class="myDiv">A Div</div>
JS
$('.myDiv').animate({
'margin-left':'50px'
}, 500, function(e){
$('.myDiv').animate({
'margin-left':'0px'
}, 500)});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With