javascriptjquerysettimeoutremoveclass

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


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);


Solution

  • 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);