setTimeout() doesn't work with jQuery(this)

84 Views Asked by At

I've got this piece of script here, where I'd like to slide up my ul element, then after the slide up executed, I'd like to remove the "open" class for CSS reasons. What am I doing wrong?

jQuery(this).parent().children("ul").slideUp(500);
setTimeout(function(){
  var elementToRemove = jQuery(this).parent();
  elementToRemove.removeClass("open");
}, 500);

3

There are 3 best solutions below

2
Sirko On BEST ANSWER

this inside you callback function refers to the global object and not the event target.

Two solutions:

Use arrow functions (which preserve the this context):

jQuery(this).parent().children("ul").slideUp(500);
setTimeout(() => {
  var elementToRemove = jQuery(this).parent();
  elementToRemove.removeClass("open");
}, 500);

Or save a link to the this object:

jQuery(this).parent().children("ul").slideUp(500);
let that = this;
setTimeout(function(){
  var elementToRemove = jQuery(that).parent();
  elementToRemove.removeClass("open");
}, 500);
0
Vladu Ionut On

Solution 1

Use bind to pass the context to the function

jQuery(this).parent().children("ul").slideUp(500);

var func = function(){
  var elementToRemove = jQuery(this).parent();
  elementToRemove.removeClass("open");
}
setTimeout(func.bind(this),500);

Solution 2

jQuery(this).parent().children("ul").slideUp(500);
var self = this;
setTimeout(function(){
  var elementToRemove = jQuery(self).parent();
  elementToRemove.removeClass("open");
}, 500);
0
ibrahim mahrir On

jQuery animations allow for an additional optional pararameter (a callback) called complete in the docs that will be executed once the animation is done. You can use it like this:

jQuery(this).parent()
            .children("ul")
            .slideUp(500, function(){
                var elementToRemove = jQuery(this).parent();
                elementToRemove.removeClass("open");
            });