1

I'm building a javascript application and there is sometimes a need to do a trigger-click. Calling the trigger, the app wait once for an animation end and run a few lines codes after that. But the script doesn't wait until the animation end and continues with other code.

The problem is hard to describe, so here's my code:

var $output = $('#output');

$('#link-1').click(function(){
    $('#link-2').trigger('click');
    $output.append('<div>Second output</div>');
});

$('#link-2').click(function(){
    var $obj = $(this);
    $obj.toggleClass('active');

    $obj.one('transitionend', function(){
        $output.append('<div>First output</div>');
    });
});

The result looks like:

<div id="output">
    <div>Second output</div>
    <div>First output</div>
</div>

You can try it here: http://jsfiddle.net/MKZvZ/1/

How can i achieve that First output appears before Second output?

First output and Second output are just basic examples, in effect the app doe's some logic work.

Slevin
  • 4,268
  • 12
  • 40
  • 90

2 Answers2

0

You can use setTimeout function to delay a process

window.setTimeout(function() {
        // this will execute 1 second later
    }, 1000);

Please refer the below link. Here they can explain how to delay the execution. You can delay your execution until your animation get over.

http://stackoverflow.com/questions/4912655/javascript-how-to-put-a-simple-delay-in-between-execution-of-javascript-code

Arun Kumar T
  • 620
  • 4
  • 12
  • 26
0

Not an elegant solution, but nevertheless

http://jsfiddle.net/MKZvZ/2/

var $output = $('#output');

$('#link-1').click(function(){    
    var func = function(){
        $output.append('<div>Second output</div>');
    }
    $('#link-2').trigger('click',func);
});

$('#link-2').click(function(event,func){
    var $obj = $(this);
    $obj.toggleClass('active');

    $obj.one('transitionend', function(){
        $output.append('<div>First output</div>');
        func.call();
    });

});
gvmani
  • 1,580
  • 1
  • 12
  • 20