Pregunta

I have create a function to animate one div then fade another on click. When I click again the animation is to run in reverse. The function works but the animate part jumps to its designated point without animating and only when run in reverse.

I believe the left margin is being set prior to the fade and so jumps to the set point after the fade completes but I do not know how to fix this.

MY QUESTION

How to run a fade followed by an animate with two different targets on click of a button. Then on toggle click to run in reverse. jquery 1.9

var toggle = false;
$('#btn1, #btn2').click(function(){
    $('#CtrCol').animate({marginLeft: toggle ? 251 : 0},{complete: function(){
        $('#LftCol').fadeToggle();
    }}); 
    toggle = ! toggle;
});

MY SOLUTION

var flag = 0;
$('#btn1, #btn2').click(function() {
    if (flag == 0) {
        $('#LftCol').fadeOut({complete: function(){
            $('#CtrCol').animate({marginLeft: 0});
        }});
        flag = 1
    }
    else if (flag == 1) {
        $('#CtrCol').animate({marginLeft: 251},{complete: function(){
            $('#LftCol').fadeIn();
        }});
        flag = 0
    }
});
¿Fue útil?

Solución

You could just set a flag to know in which direction to run the animation and check it in the .click function

if (flag == "right") // run right anim
  flag = "left"
else // run left anim
  flag = "right"

Edit: Keep the callback

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top