tbarho
tbarho

Reputation: 11

jQuery hover infinite loop

I'm trying to use .hover to make an HTML element look like it's glowing. My code looks like:

var glow = $('<div class="glow">...</div>');

$(this).hover(function() {
   glow.fadeIn();
}, function() {
   glow.fadeOut();
}

The effect I'm getting is that the fades just keep repeating over and over again on mouseover in an infinite loop. When I look at the console, the hoverIn and hoverOut handler functions just keep getting called.

Any ideas what might be going on?

Thanks!

Upvotes: 1

Views: 1606

Answers (1)

Kyle Humfeld
Kyle Humfeld

Reputation: 1907

I think you want to use this code instead:

var glow = $('<div class="glow">...</div>');

glow.hover(function() {
   $(this).fadeIn();
}, function() {
   $(this).fadeOut();
}

or

var glow = $('<div class="glow">...</div>');

glow.hover(function() {
   glow.fadeIn();
}, function() {
   glow.fadeOut();
}

I believe right now your $(this) is ambiguous, and is probably not putting the hover() handler on the right object.

It's also possible that you've omitted something important here (as in, where is glow put into the DOM).

If worse comes to worse, you can skip hover entirely and just use mouseover and mouseout instead, or if you want to get really manual about the whole thing, you can use bind with the mouseover and mouseout events.

Actually, since you're seeing repetitive action on a single mouseover event, that might indicate that you've somehow bound many instances of your single hover handler to the glow object. You can use unbind to remove the current handler before binding a new one if this ends up being the case, but avoiding the multiple binding is a better strategy if you can find a way to do so.

I hope this helps!

Upvotes: 2

Related Questions