agon024 agon024 - 1 month ago 21
jQuery Question

jQuery - mouseenter / mouseleave with timer not functioning

What I am trying to do is only run my code when someone has hovered on an element for 1 second.

Here is the code that I am using:

var timer;

$(".homeLinkWrap").mouseenter(function() {
timer = setTimeout(function(){
$(this).find('.homeLinkNfo').removeClass('flipOutY').addClass('flipInY').css({opacity: '1'});
console.log('in');
}, 1000);
}).mouseleave(function() {
$(this).find('.homeLinkNfo').removeClass('flipInY').addClass('flipOutY');
console.log('out');
clearTimeout(timer);
});


The first part (mouseenter) IS NOT functioning and DOESN'T remove the class and then add the new one. The second one (mouseleave) IS functioning properly and DOES remove the class and add the new one.

I am guessing it is because I am targeting $(this) which is the current element being hovered over and since it is in a timer function jQuery doesn't know which element $(this) is referring to.

What can I do to remedy this?

Answer

I think it is because you are calling $(this) inside the setTimeout function. You need to do something like this:

$(".homeLinkWrap").mouseenter(function() {
    var $self = $(this);
    timer = setTimeout(function(){
       $self.find('.homeLinkNfo').removeClass('flipOutY').addClass('flipInY').css({opacity: '1'});
       console.log('in');
    }, 1000);
});