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

Community
  • 1
  • 1
Aman Singh
  • 743
  • 1
  • 10
  • 20

2 Answers2

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);    
});
tabz100
  • 1,463
  • 11
  • 14
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/

guest271314
  • 1
  • 15
  • 104
  • 177
  • what should i do if i want to call series of functions similarly one after another ? thanks in advance – Aman Singh Jan 17 '15 at 17:05
  • @Aman See http://stackoverflow.com/questions/27206855/is-there-an-easier-way-of-chaining-different-jquery-actions-for-different-select/27216737#27216737 – guest271314 Jan 18 '15 at 06:07