Search code examples
jquerydelaymouseovermouseout

jQuery mouseover/mouseout delay, multiple elements


I have this series of parent divs (sharing the same class) that enclose a child each. When I mouseover a parent, I want to add a class to its child. When I mouseout, I want to remove that class with a 500ms delay.

I figured setTimeout was the way to go for the delay. To prevent mouseout from triggering the removeClass after I actually got back over the parent, I thought of using clearTimeout. The problem is I cannot get clearTimeout to be triggered only if the newly hovered parent is the same as the previous one. The result of this being that if I hover from parent A to parent B in less than 500ms, removeClass is not triggered on parent A (as I actually would like it to).

I hope this makes sense. Any help greatly appreciated!

var timer

$('.parent')
  .mouseover(function() {
    //clearTimeout(timer)
    $(this).children('.child').addClass('red');
  })
  .mouseleave(function() {
    that = this
    timer = setTimeout(function() {
      $(that).children('.child').removeClass('red');
    }, 500);
  });

https://jsfiddle.net/andinse/1wnp82nm/


Solution

  • You should set timeout specific to each .parent element and bind relevant context to setTimeout callback, e.g using bind() to avoid variable that closure issue:

    -DEMO-

    $('.parent')
      .mouseover(function() {
        clearTimeout(this.timer)
        $(this).children('.child').addClass('red');
      })
      .mouseleave(function() {
        this.timer = setTimeout(function() {
          $(this).children('.child').removeClass('red');
        }.bind(this), 500);
      });