Charlie74
Charlie74

Reputation: 2903

Trouble with jQuery delay on mouseenter event

This should be simple... not sure why it's giving me trouble like it is. I have a simple mouseenter function. Works fine. What I would like to do is have the function only launch after hovering for 2.5 seconds.

My working function is this...

Working script

$('.profileimage').mouseenter(function(e) {
  $(this).parent().parent().find('.profileInfo').css({'top': (e.pageY + 25),'left': (e.pageX + 25)}).fadeIn('slow');
});

Simple enough... all it does is fade in a div element I currently have hidden.

Now, to add the delay, I've wrapped this in a setTimeout(function(), because after reading some other posts on here this seems like the correct solution. So now I've got this...

Not working script

$('.profileimage').mouseenter(function(e) {
  setTimeout(function() {
  $(this).parent().parent().find('.profileInfo').css({'top': (e.pageY + 25),'left': (e.pageX + 25)}).fadeIn('slow');
  }, 2500);
});

Apparently, I'm not using the setTimeout function correctly, or I assume this would be working.

Working demo: http://jsbin.com/AqiFEQI/1/edit

Broken demo: http://jsbin.com/AqiFEQI/2/edit

If you try the working code, you'll see an ugly div pops up when hovering over Charles. In the broken sample, nothing happens.

Any help would be greatly appreciated...

Upvotes: 0

Views: 139

Answers (1)

Peter van der Wal
Peter van der Wal

Reputation: 11846

this will equal to window when the timeout-callback is called. Change to

$('.profileimage').mouseenter(function(e) {
    var elem = this;
    setTimeout(function() {
       $(elem).parent().....;
    }, 2500);
});

Updated JSBin: http://jsbin.com/AqiFEQI/4/edit

Upvotes: 3

Related Questions