Search code examples
jquerycallbackjquery-callback

Why is my jQuery callback function not responding?


With this code I would expect called back prompted in my face but instead I get nothing.

I have followed the simple examples used in tutorials like this and see no apparent different from their examples to mine. Still no success.

$.fn.mirror = function (selector, callback) {
    return this.each(function () {
        var $this = $(this);
        var $selector = $(selector);
        $this.bind('keyup', function () {
            $selector.text($this.val()); 
        });
    });
    callback();
};

$('#displayurl').mirror('.displayurl', function () {
    alert('called back');
}); 

Solution

  • Because you are returning after the first line executes. return ends the execution of a function and returns the value to the caller.

    In this case your callback function will not execute because you are returning $.each function and terminating the execution of the function. Try

    $.fn.mirror = function (selector, callback) {
        this.each(function () {
            var $this = $(this);
            var $selector = $(selector);
            $this.bind('keyup', function () {
                $selector.text($this.val()); 
            });
        });
        callback();
        return; //you could return whatever is useful for you if you want.
    };
    
    $('#displayurl').mirror('.displayurl', function () {
        alert('called back');
    }); 
    

    And I would also suggest you read up on basics of programming.