sazr
sazr

Reputation: 25928

JQuery FadeIn/Out Only Works One Time

I have a very simply div that uses JQuery to fade in when the mouse hovers over the div. Then when the mouse leaves the div it fades back out.

My Problem: The fade in/out only works once. When I place my mouse over the div the second time it doesn't fade in.

Whats going wrong? JSFiddle: http://jsfiddle.net/hWyUn/3/

<div id="test" style="opacity: 0; width: 100px; height: 100px; background-color: red;">
</div>

$("#test").mouseenter(function()
                    {
                        $(this).css("opacity","1").fadeIn();
                    });

$("#test").mouseleave(function()
                    {
                        $(this).fadeOut();
                    });

Upvotes: 3

Views: 3452

Answers (5)

bpile
bpile

Reputation: 380

It will work only if element is hidden. You can set the element's display to none by doing $(element).css('display', 'none') before $(element).fadeIn() :)

Upvotes: 1

Tabetha Moe
Tabetha Moe

Reputation: 480

Fixed your problem. Check out the fiddle...

jsFiddle

Upvotes: 0

Dropped43
Dropped43

Reputation: 345

You could always try using the the jQuery's Animate to animate the opacity, instead of fading in and out. Might be shorter code.

Animating the opacity will not set the display to none, so you can still fiddle around with it after it is faded out.

See my jsFiddle here

Upvotes: 0

Timeout
Timeout

Reputation: 7909

See the jQuery docs. fadeOut() will set the display property to none once it finishes. Effectively removing it from your page.

http://api.jquery.com/fadeOut/

Upvotes: 3

Skylar Anderson
Skylar Anderson

Reputation: 5703

Using fadeTo Worked for me:

$("#test").mouseenter(function()
    {
        $(this).fadeTo("slow", 1);
    });

$("#test").mouseleave(function()
    {
        $(this).fadeTo("slow", 0);
    });

Here: http://jsfiddle.net/hWyUn/4/

Upvotes: 4

Related Questions