Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
461 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...