Ando
Ando

Reputation: 103

Jquery Issue with fadeTo on hover

So basically I am trying to have div.show fade in on hover and then when you stop hovering, have it fade back to an opacity of 0.

However, I cannot get the div to fade back to 0 when you stop hovering.

Here is my code:

$(document).ready(function(){
    $("div.post.photo").live('hover', function() {
        $(this).children("div.show").fadeTo("slow", .7);
    }, function(){
        $(this).children("div.show").fadeTo("slow", 0);
    });
});

Thank you

Upvotes: 0

Views: 164

Answers (4)

jfriend00
jfriend00

Reputation: 707308

I find that this works if you use .hover() instead of .live(), so I think the issue is that .live() doesn't support the hover event, perhaps because .live() only has one handler function, not two.

In jQuery 1.7+, this seems to work (breaking it up into two event handlers and modernizing to .on()):

$(document).ready(function(){
    $(document.body).on("mouseenter", "div.post.photo",
        function() {
            $(this).children("div.show").fadeTo("slow", .7);
        }
    );

    $(document.body).on("mouseleave", "div.post.photo",
        function() {
            $(this).children("div.show").fadeTo("slow", .0);
        }
    );
});

You can see it work here: http://jsfiddle.net/jfriend00/YV2nU/.

FYI, I switched to .on() because .live() is deprecated in jQuery 1.7+.

Upvotes: 1

aziz punjani
aziz punjani

Reputation: 25776

You need to explicitly check for the mouseenter and mouseleave events using the event.type. You shouldn't need to bind them twice.

$(document).ready(function(){
    $("div.post.photo").live('hover', function(event) {

        if( event.type === 'mouseenter') 
            $(this).children("div.show").fadeTo("slow", .7);
        else if( event.type === 'mouseleave' )
            $(this).children("div.show").fadeTo("slow", 0);
    });
});

Here's a fiddle. Personally i would use .on but i'm not sure what version of jQuery you are using.

Upvotes: 2

Nate B
Nate B

Reputation: 6356

Your problem is that hover is not a Javascript event, it is JQuery shorthand for the mouseenter and mouseleave events, so it can't be used in the live method like that. You need to bind them separately. Additionally, you should note that the .live() method is deprecated. The JQuery documentation gives instruction on what methods are better to use.

Upvotes: 0

Ilia G
Ilia G

Reputation: 10211

I am pretty sure you should be fading it back to 1, not 0. Also live() only takes one handler. You need to append mouse out event separately.

fiddle

Upvotes: 1

Related Questions