Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery events don't work when html is injected

I have something like this:

function SetTableBehavior() {
    $(".displayData tr").hover(function(e) {
        $(this).children().addClass('displayDataMouseOver');
    }, function () {
        $(this).children().removeClass('displayDataMouseOver');
    });
    $(".displayData tr td").click(function(e) {
        var rowsSel = $(".displayData .displayDataRowSelected");
        for (var i = 0; i < rowsSel.length; i++) {
            var rowSel = rowsSel[i];
            $(rowSel).children().removeClass("displayDataRowSelected");
        }
        $(this).parent().addClass('displayDataRowSelected');
        var p = $(this).parent();
        p.children().addClass('displayDataRowSelected');
    });
}

When the body of the table is injected neither hover or click work. If i use

$(".displayData tr td").live('click',function(e) {

the click event works but

$(".displayData tr").live('hover',function(e) {

doesn't work

What is the solution so that hover works. Thanks.

It seems to work like this:

function SetTableBehavior() {
    $(".displayData tr").live('mouseenter', function (e) {
        $(this).children().addClass('displayDataMouseOver');
    }).live('mouseleave', function(e) {
        $(this).children().removeClass('displayDataMouseOver');
    });
    $(".displayData tr td").live('click',function(e) {
        var rowsSel = $(".displayData .displayDataRowSelected");
        for (var i = 0; i < rowsSel.length; i++) {
            var rowSel = rowsSel[i];
            $(rowSel).children().removeClass("displayDataRowSelected");
        }
        $(this).parent().addClass('displayDataRowSelected');
        var p = $(this).parent();
        p.children().addClass('displayDataRowSelected');
    });
}
like image 314
gigi Avatar asked Jan 18 '23 16:01

gigi


2 Answers

$(".hoverme").live("mouseover mouseout", function(event) {
  if ( event.type == "mouseover" ) {
    // do something on mouseover
  } else {
    // do something on mouseout
  }
});

From here: http://api.jquery.com/live/

There is no event called "hover" so you can't use it with live or bind. It is just a "short-cut" that jQuery implemented for us.

like image 183
Adam Terlson Avatar answered Jan 30 '23 03:01

Adam Terlson


You cannot use hover with live. You'll have to split it up in 2 separate event listeners: one for mouseenter, and another one for mouseleave.

Additionally, in your situation, you don't need live. Use delegate, which is much better for performance:

$(".displayData").delegate('tr', 'mouseeneter',function(e) {
    $(this).children().addClass('displayDataMouseOver');
})
.delegate('tr', 'mouseleave',function(e) {
    $(this).children().removeClass('displayDataMouseOver');
});
like image 33
Joseph Silber Avatar answered Jan 30 '23 04:01

Joseph Silber