Reputation: 15
hey i am having a function in jquery to move a div element right and then left on click . but at the seocnd click as it should execute the same action again. it is just executing last line of function . my code is
$(document).ready(function(){
$('#circle').click(function() {
$('#rocky').animate({right:"+=75%"},500);
$('#rocky').animate({left:"+=75%"},500);
});
});
on first click the function works well but on the second click it is just executing the last lne that is animate left nd my div is moving left. which i don't want . i just want that on every click it should execute like on first click
Upvotes: 0
Views: 88
Reputation: 388316
Since you are adding 75%
to the right, to move it to the original position subtract 75%
from the right value
$('#circle').click(function() {
$('#rocky').animate({right:"+=75%"}, 500);
$('#rocky').animate({right:"-=75%"}, 500);
});
Demo: Fiddle
Upvotes: 1
Reputation: 331
jQuery's animate()
method is non-blocking, which means that as soon as it starts running, the code that follows it will start running as well, without waiting for the animation to complete. For your purposes, you'll want to use a callback function, which will run only after the initial animation completes.
$(document).ready(function(){
$('#circle').click(function() {
$('#rocky').animate({right:"+=75%"},500, function () {
$('#rocky').animate({left:"+=75%"},500);
});
});
});
Though your CSS might need a little work as well. I'd suggest using only 'left' or 'right' instead of both, adding or subtracting as necessary.
$(document).ready(function(){
$('#circle').click(function() {
$('#rocky').animate({left:"+=75%"},500, function () {
$('#rocky').animate({left:"-=75%"},500);
});
});
});
The jQuery animate()
docs for reference: http://api.jquery.com/animate/
Upvotes: 2