sheriffderek
sheriffderek

Reputation: 9043

Proper syntax for callback on custom javascript function / jQuery

I've simplified this down, and yes... I know that fadeIn is a strange example... but that is part of the point.

How do I make a call back function on a custom function - or a function with nothing passed through it... for example - what if there is no argument? Here is a fiddle to illustrate my confusion -

I have broken up this monster set of callbacks into little groups, and I want to chain them - but I'm definitely missing something...

jQuery

// An example function

function sheriff(speed) {
    $('.thing').fadeIn(speed);
}

$('button').on('click', function() {

    sheriff(1000, function() {
        $('body').css('background-color', 'red');
    });

});

EDIT

This is my actual code, with the proper callback in place. I over simplified with my first example, and it didn't show a complicated enough use - and so - for others I'll leave this here.

jQuery

function pullInSocialButtons(speed, callback) {

    var facebook    = $('.toy-box-top .social-links li:nth-of-type(1)');
    var twitter     = $('.toy-box-top .social-links li:nth-of-type(2)');
    var google      = $('.toy-box-top .social-links li:nth-of-type(3)');
    var email       = $('.toy-box-top .social-links li:nth-of-type(4)');

    facebook.fadeIn(speed, function() {
        twitter.fadeIn(speed, function() {
            google.fadeIn(speed, function() {
                email.fadeIn(speed, callback); // CALLBACK
            });
        });
    });

} // end

Then in this other function --->

$('.some-thing').fadeIn(500, function() {

    pullInSocialButtons(50, function() {
      setTimeout(function () {

        $('.porthole').fadeIn(500);

      }, 1000);
    });

});

Upvotes: 2

Views: 167

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

In your sheriff, you can receive the second param as the second parameter like

// An example function

function sheriff(speed, callback) {
    $('.thing').fadeIn(speed, callback);
}

$('button').on('click', function() {

    sheriff(1000, function() {
        $('body').css('background-color', 'red');
    });

});

Demo: Fiddle

Upvotes: 6

Related Questions