Aman Singh
Aman Singh

Reputation: 753

Why the callback in javascript is not working?

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

Upvotes: 0

Views: 70

Answers (2)

guest271314
guest271314

Reputation: 1

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/

Upvotes: 2

tabz100
tabz100

Reputation: 1473

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);    
});

Upvotes: 4

Related Questions