0

I am trying to create hover effect with callback function. It seems that the effect can only be trigged on the callback function but not the init hover. I was wondering if someone here can help me out. Thanks a lot.

$("img").live("hover", function () {
    // hover in
    $(this).css("z-index", 1);
    $(this).animate({
        height: "35%",
        width: "35%",
        left: "-=50",
        top: "-=50"
    }, "fast");
}, function () { //only the following codes will be triggered.
    // hover out
    $(this).css("z-index", 0);
    $(this).animate({
        height: "15%",
        width: "15%",
        left: "+=50",
        top: "+=50"
    }, "fast");
});

The img are generated via ajax call, not sure if it's relevant

<div id='image_layout'>
    <img src='a.jpg' />
    <img src='b.jpg' />
    <img src='c.jpg' />
</div>  
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Rouge
  • 4,181
  • 9
  • 28
  • 36
  • Only the [`.hover()`](http://api.jquery.com/hover/) shorthand supports 2 functions like that. `live` doesn't work that way. – gen_Eric Aug 02 '12 at 17:05

2 Answers2

3

live() is deprecated, and it does'nt really work that way, but if you are using jQuery 1.7+ you should be using on() to delegate the event to the closest non dynamic parent, I'll use document in the example, you'll replace document with the closest parent to the image that is'nt inserted with Ajax, probably #image_layout if that element is not inserted dynamically :

$(document).on({
    mouseenter: function() {
        $(this).css("z-index", 1).animate({
                height: "35%",
                width: "35%",
                left: "-=50",
                top: "-=50"
            }, "fast");
    },
    mouseleave: function() {
        $(this).css("z-index", 0).animate({
                height: "15%",
                width: "15%",
                left: "+=50",
                top: "+=50"
            }, "fast");
    }
}, "img");

On another note, using += and percentages in your animations will in many cases cause you nothing but grief.

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • what would you recommend for my height and width without +=? Thanks a lot. – Rouge Aug 02 '12 at 17:17
  • Percentages is usually fine if you're in control over your CSS, positioning of elements etc, and now how it all works. += can cause problems, especially when using stop(), but it can be useful sometimes, so it's really up to you. If it works, fine for you, otherwise using a pixel value is the option with the least problems in my opininon. – adeneo Aug 02 '12 at 17:51
1

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

Try on!

Also your params are wrong, the second param should be data nog some kind of callback see for more information: http://api.jquery.com/live/

Jonas Geiregat
  • 5,214
  • 4
  • 41
  • 60