views:

1034

answers:

2

I am dynamically appending HTML to a webpage and I'm also using jQuery to manage stuff.

When I add HTML code, jQuery ignores its existence.
For example:

$("td.elementToClick").click(...

Will work great with jQuery. But if somewhere in the code I append:

$("tr#myRowToAppend").append("<td class="elementToClick>...</td>");

jQuery will ignore this new element if I click on it.

As jQuery associates the events after the page finishes loading, I need one of two solutions: - Force the DOM to re eval the page without changing the current layout (I don't wish a refresh, so location.reload() is out of the question). - Force jQuery to add this new element to it's internal event manager.

I don't wish to use onclick="blabla()", I really need to use jQuery.

How can I accomplish this?

+7  A: 

What you are looking for is jQuery live. From docs description: "Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events."

There is also a plugin liveQuery that supports a wider range of events if you want.

Nadia Alramli
live won't solve everything.
Chad Grant
@Chad, can you elaborate?
bendewey
@bendewey - live doesn't currently work with all events. As of 1.3 it works with click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, and keyup, but not blur, focus, mouseenter, mouseleave, change, or submit.
tvanfosson
@tvanfosson, that's correct. But he was only speaking about the click event which is supported. I'll add a link for livejquery plugin if he was interested in more events. But usually I prefer core solutions whenever possible
Nadia Alramli
The click was one example, but this pretty much fixed the problem, tks
fmsf
There are more gotchas than just the missing events. Some browsers still wont work with live() events if you are not cloning properly
Chad Grant
+2  A: 

the live() method will alleviate most of your headaches.

I see this happening more often in IE and with cloned elements, to support IE you have to be much more careful with DOM manipulation.

I also see alot of questions on SO with people having issues of copying/moving dom elements to new parts of the dom without cloning it first, which doesn't workout so well in IE.

So you can use live or when you have to handle events from dynamically inserted DOM elements, make sure you clone them with clone(true) to specify you want the events copied:

$("body").append('<div id="one"></div>");

$("#one").mouseover(function(){});

$("body").append( $("#one").clone(true).attr('id','two') );
Chad Grant