javascriptjquerythis

Custom jQuery plugin


I quickly wrote this jquery plugin. When I pass it a $element it slides up, but then it breaks on this.empty() claiming this is not a function. What's the problemo?

(function ( $ ) { 
 $.fn.slideUpEmpty = function(t, callback){
        this.slideUp(t, function(){
            this.empty();   
            if(callback){
                callback(); 
            }
        });
    }

}( jQuery ));

Use

$('#somediv').slideUpEmpty(500, function(){

});

Solution

  • Inside the slideUp callback, this refers to a DOM element, as described in the documentation:

    The callback is not sent any arguments, but this is set to the DOM element being animated.

    So if you want to call a jQuery method on it, you have to pass it to jQuery first:

    $(this).empty();
    

    That would empty each element after it was done animating, since the callback is executed for each selected element.

    If you want to empty them only after all of them are done animating, you can use a promise:

    this.slideUp(t).promise().done(function() {
        this.empty(); // no `$(this)` here, `this` is already a jQuery object
    });
    

    This executes the callback passed to .done only once after all elements finished animating.