views:

365

answers:

3

I have a div element that on the click of a link slide in from the right and slides to the left, the works great, I am now trying to get so that if the link is clicked again it runs the animation in reverse, I have tried add a class to the link when the animation runs and then doing the same animation but backwards, but that does not work I get no response, can any give me any tips etc?

    $('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;
});
+6  A: 

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
});
John McCollum
A: 

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/

EmKay
A: 
$('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;
});
andres descalzo