-1

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(){

});
4
  • Have you tried $(this).empty() ? Commented Sep 12, 2014 at 2:10
  • No, because I don't understand why slideUp can accept this without $() Commented Sep 12, 2014 at 2:11
  • Inside a jQuery plugin method, this refers to the jQuery object. Inside a jQuery method callback,this refers to the DOM element. Commented Sep 12, 2014 at 2:11
  • 1
    This question is similar to: How to access the correct `this` inside a callback. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Nov 29, 2024 at 11:03

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.