rob.m
rob.m

Reputation: 10611

Mouseenter and mouseleave flashing

When I mouseeneter the box becomes visible but then it keeps fading on and off even tho my mouse stays on the box, what am I doing wrong?

jQuery

    geoThumb = $(".geoThumb");
    geoThumb.each(function(){
        $(this).mouseenter(function() {
            $(".infoBox").fadeIn(500);
        }).mouseleave(function(){
            $(".infoBox").fadeOut(500);     
        });
    });

Upvotes: 2

Views: 648

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206689

You don't need the each() at all.
Use .hover() (in this specific case)
Use .stop() to clear previous animation buildups on every new event.
Use .fadeToggle() (in combination with .hover())

geoThumb = $(".geoThumb");

geoThumb.hover(function() {
     $(".infoBox").stop().fadeToggle();
});

Also I'm not sure if you're specific enough with your $(".infoBox") selector, cause it's a collection of all .infobox elements, if you need to animate only one specific element you need to take a look at some other DOM traversal methods like .find()

Upvotes: 0

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94409

Add .stop before .fadeIn and .fadeOut.

$(".geoThumb").mouseenter(function() {
    $(".infoBox").stop().fadeIn(500);
}).mouseleave(function(){
    $(".infoBox").stop().fadeOut(500);     
});

Demo: http://jsfiddle.net/DerekL/R4F9T/

It flashes because the animations are queued when the animations before it are not finished. To prevent this behavior, .stop is designed and you can use this to clear all queued animations.

Quote from jQuery Docs

The usefulness of the .stop() method is evident when we need to animate an element on mouseenter and mouseleave.

Upvotes: 3

asdf
asdf

Reputation: 3067

.mouseenter and .mouseleave isn't the most powerful way to handle hover events in query. Try using .hover() which takes 2 functions, the first one runs when the mouse enters the element and one when it leaves. http://api.jquery.com/hover/

Upvotes: 0

Related Questions