Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  154] [ 7]  / answers: 1 / hits: 34842  / 15 Years ago, mon, january 25, 2010, 12:00:00

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;
});

More From » jquery

 Answers
81

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.)


[#97753] Thursday, January 21, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
haleeg

Total Points: 703
Total Questions: 100
Total Answers: 98

Location: Dominica
Member since Sat, Nov 5, 2022
2 Years ago
;