views:

32

answers:

2

I've recently converted my code to produce dynamically generated results. The below code worked fine to toggle the control_hover class.

Previous Code

$(".control").hover(function () {$(this).addClass("control_hover");},function () {$(this).removeClass("control_hover");});

However, now with the live code, it doesn't seem to execute the removeClass part.

New Code

$(".control").live('hover',function () {$(this).addClass("control_hover");},function () {$(this).removeClass("control_hover");});

I'm obviously doing something incorrectly. Any help would be appreciated.

+3  A: 

When using .live() with hover, it doesn't take 2 functions. You need to send one function that tests for which event fired.

Try it out: http://jsfiddle.net/RpV6y/

$(".control").live('hover',function (evt) {
      if(evt.type == 'mouseover') {
          $(this).addClass("control_hover");
      } else {
          $(this).removeClass("control_hover");
      }
 });

Another option would be to use toggleClass. It will still fire for both events.

Try it out: http://jsfiddle.net/RpV6y/1/

$(".control").live('hover',function (evt) {
     $(this).toggleClass("control_hover");
});
patrick dw
Thank you, makes sense now. Will accept the answer as soon as stack lets me.
st4ck0v3rfl0w
@st4ck0v3rfl0w - You're welcome. :o) And FYI, you need jQuery 1.4.1 or later to use `hover` with `.live()`.
patrick dw
+4  A: 

Live can accept only one handler. Try:

$(".control").live('mouseenter', enterhandler).live('mouseleave',leavehandler);

http://api.jquery.com/live/ see caveats section

skalee