1

Possible Duplicate:
Jquery live() vs delegate()

I am having some problems applying JQuery to functions that I add to the DOM after the page is loaded. I am using the following code to add new rows to a table body:

  $("tbody").load("php/create_rows.php?" + $.param({ "type": "unique", "unit": "day", "interval": 2 }));

It works well. The rows get added, but Jquery functions that work on the rows in the table body do not affect the new rows. For example, mouseovers on rows are supposed to have a class applied to them that changes the background color:

  $('tbody tr').hover(function() {
    $(this).find('td').addClass('hover');
  }, function() {
    $(this).find('td').removeClass('hover');
  });

It is not working, though. It works for code that already appears on the page, code that is not generated from Jquery.

Community
  • 1
  • 1
egidra
  • 347
  • 2
  • 9
  • 18
  • ...or [jquery live hover](http://stackoverflow.com/questions/2262480/jquery-live-hover) – Shef Jun 27 '11 at 20:33

2 Answers2

2

try replacing your code:

  $('tbody tr').hover(function() {

with

$('tbody tr').live('hover', function(){

That should make the new stuff work.

YonoRan
  • 1,718
  • 9
  • 7
  • not sure if live('hover') works with two functions. It might need to be one function, or change hover for mouseenter and mouseleave – Rodolfo Jun 27 '11 at 20:55
  • I just checked if it works, and it does. Thank you though, cause once you mentioned it it made me think... But it seems to works. – YonoRan Jun 27 '11 at 21:10
2

You must wrap your

$('tbody tr').hover(function() {

into a function and when you add a dynamic element to the DOM you need to call the function like this

function something (){
   $('tbody tr').hover(function() {
    $(this).find('td').addClass('hover');
  }, function() {
    $(this).find('td').removeClass('hover');
  });
}

$("document").append(someelement);
something();

example done with a input field http://jsfiddle.net/MKcaH/1/

and come to think about it you could use [1]: http://api.jquery.com/delegate/ "delegate"

John
  • 1,309
  • 2
  • 12
  • 24