views:

1194

answers:

1

I have some <tr> elements on my page with a click() event attached to an image that sits inside each one. I use this code

$(this).clone(true).appendTo("table#foo");

to do the following:

  • copy those <tr>s into a different table
  • preserve the click events on the images inside the <tr>s (because of the true argument)

All of that works fine. Now I have added a jQuery Listen event to those <tr>s, so that a user doesn't have to aim precisely: he/she can click anywhere on the <tr> and I can pass the click to the image.

It's coded like this:

$('tr.record').listen('click','td',function(){
  $(this).parent().find("img.clickable").click();
});

The listen() event works fine on the original item, but on the cloned item, the listen() event fails. The image's click event still works fine.

Here is what Firebug tells me:

m(this, e.type) is undefined

...and it references line 9 of jquery.listen-1.0.3-min.js.

How can I can make the listen() event work on the cloned elements?

Update

By default, jQuery doesn't copy events on cloned elements, but this plugin is made to do that.

Meanwhile, the author of the listen() plugin suggested a different strategy - see my answer below.

+1  A: 

Ariel Flesler, creator of the listen() plugin, gave me this advice via email:

"I think this can be solved in another way. The idea of Listen (and event delegation) is to actually avoid all the copying of events for new elements."

"You could simply do:"

$('table#foo').listen('click','td',function(){
 $(this).parent().find("img.clickable").click();
});

"Or even:"

$.listen('click','td',function(){
 $(this).parent().find("img.clickable").click();
});

"The first example will use the table as listener. In the 2nd one, the <html> tag is used. So no matter if you add new td/tr/tables. It'll still work."

Nathan Long