开发者

jQuery reversing animation on second click

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 backward开发者_JS百科s.

    $('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/


$('a.contact').click(function(e) {
   e.stopPropagation();
   var dir = '';

   if ($(this).hasclass('to-left'))
   {
      dir = 'to-rigth';
      $(this).removeClass('to-left');
   } 
   else //ini or has class to rigth
   {
      dir = 'to-left';
      $(this).removeClass('to-rigth');
   }

   dir = $(this).addclass(dir);

   if (dir=='to-left')
   {
      //you code to left
   }
   else 
   {
      //you code to rigth
   }

    return false;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜