Search code examples
jqueryjquery-callback

How to write JQuery callback function


My callback function is not working, I want to run test() after configReq()

$(document).ready(function() {
 configReq($(this).attr('href'), test);
});

var test = function() {
 alert('hi');
};

 function configReq(thisUrl) {
    $('.progress').empty();
    $('.progress').append('<div class="progress-bar bg-success" style="width: 0%; display: block;"></div>');            
}

Please let me know where i am wrong...?


Solution

  • Like this:

    $(document).ready(function() {
        configReq('Some item', test);
    });
    
    function test() {
        console.log('Callback executed');
    };
    
    function configReq(thisUrl, callback) {
        console.log('Executing configReq');
        if (callback) callback();
    }
    

    DEMO