0

I want to call the second function after first is completed

function first(callback) {
     alert('called first');
     $('.fillColor1').animate({
         height: '50px'
     }, 600);
 }

function second() {
    alert('called second');
    $('.fillColor2').animate({
        height: '50px'
    }, 600);
}

$('button').click(function() {
    first(second);    
});

Here is the code what i want on jsfiddle

I got this problem then i searched for this and landed to this link

Execute jquery function after another function completes

Please let me know, is any mistake am i doing

Thanks in advance

1
  • 1
    You are not using callback in your first function. Commented Jan 17, 2015 at 16:38

2 Answers 2

4

You need to actually call the callback after the first function:

function first(callback) {
     alert('called first');
     $('.fillColor1').animate({
         height: '50px'
     }, 600, callback);
}

function second() {
    alert('called second');
   //Do Code
}

$('button').click(function() {
    first(second);    
});
Sign up to request clarification or add additional context in comments.

2 Comments

but by using this both function is being called at the same time i want to all the second one after first is completed
The jQuery animate method takes in a callback so you pass in the callback
2

Edit, Updated

function first(callback) {
     alert('called first');
     $('.fillColor1').animate({
         height: '50px'
     }, 600, callback);
}

function second() {
    alert('called second');
    $('.fillColor2').animate({
         height: '50px'
     }, 600);
}

$('button').click(function() {
    first(second);    
});

jsfiddle http://jsfiddle.net/zqgfz54b/1/

Alternatively

function fx(elem, callback) {
     alert('called ' + elem[0]);
     $('.fillColor' + elem[0])
     .animate({
         height: '50px'
     }, 600, function() {
       elem.splice(0, 1);
       callback.call($, elem)
     });
};

$('button').click(function() {
    fx.call($, [1, 2], fx);    
});

jsfiddle http://jsfiddle.net/zqgfz54b/2/

2 Comments

what should i do if i want to call series of functions similarly one after another ? thanks in advance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.