st4ck0v3rfl0w
st4ck0v3rfl0w

Reputation: 6755

jQuery .live() question

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.

Upvotes: 2

Views: 290

Answers (2)

skalee
skalee

Reputation: 12675

Live can accept only one handler. Try:

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

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

Upvotes: 4

user113716
user113716

Reputation: 322492

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");
});

Upvotes: 3

Related Questions