Reputation: 11
I would like to make a div slide to the right on its first click and when its clicked again, I'd like it to return to the original position
I have the following but the div doesnt move and console.log shows clicked-2 even on the first click.
$('.note-title').click(function(){
console.log("clicked-1");
$(this).animate({'margin-left':'200px'},200);
},function(){
console.log("clicked-2");
$(this).animate({'margin-left':'0px'},200);
});
Upvotes: 1
Views: 139
Reputation: 95022
Note This method is depreciated. You should use Lix's solution.
Use .toggle
$('.note-title').toggle(function(){
console.log("clicked-1");
$(this).animate({'margin-left':'200px'},200);
},function(){
console.log("clicked-2");
$(this).animate({'margin-left':'0px'},200);
});
With .click
, all passed in callbacks will get triggered with each click, one after the other.
Upvotes: 1
Reputation: 47966
What about simply using a boolean flag?
var clickOne = true;
$('.note-title').click(function(){
if (clickOne){
$(this).animate({'margin-left':'200px'},200);
}else{
$(this).animate({'margin-left':'0px'},200);
}
clickOne = !clickOne;
}
Each click toggles the value of the flag and executes a different part of the conditional expression.
Upvotes: 4