I have a div element, that on click event, a link slides in. This works great, except I am now trying to get it so that if the link is clicked a second time, the animation reverses to its original state.
I have tried to add a class to the link, but when the animation runs it ends up doing the same animation but backwards.
$('a.contact').click(function() {
$('#contact').animate({marginLeft:'500px'}, {queue:false, duration:'7000'});
$('#contact').animate({width:'500px'}, {duration:'7000'});
$('a.contact').css()
$('a.contact').animate({marginLeft:'-500px'}, '250');
$('a.contact')addClass('open');
return false;
});
The easiest way to handle this would be to use jQuery toggle. This allows you to activate two functions on alternate clicks.
$('a.contact').toggle(
function(){
// odd clicks
},
function(){
// even clicks
});
...And a quick jsFiddle to demonstrate.
Note that this uses jQuery's toggle event handler, not the animation effect of the same name.
Note #2: As per the documentation, toggle() was removed in jQuery 1.9. (That is, the method signature that allowed you to pass multiple functions which were activated on alternate clicks.)
First of all you are missing a . in the addClass line. This is the correct version: $('a.contact').addClass('open');
Anyway, I would do like this:
// Bind the click event with the live function
$('a.contact:not(.open)').live('click', function() {
// Animate box as wanted and add a class to indicate that the box is open.
// ... Code to animate goes here ...
$(this).addClass('open');
});
$('a.open').live('click', function() {
// Reverse animation and remove class
// ... Code to reverse animation goes here ...
$(this).removeClass('open');
});
The reason that you need to bind with the live function is that the class "open" is not added to any elements when the regular .click() binding takes place.
Read about the live method here: http://api.jquery.com/live/
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