views:

1301

answers:

2

I'm wondering if this is possible in JQuery.

I have some Javascript code that creates DOM objects on the fly, in response to user actions. Some of those DOM objects are in a specific structure - the container always has the same "class" attribute.

What I'd like to do is, every time a new instance of a DOM object with class "X" is created, I want the same piece of Javascript code to execute. That code will add an "onclick" event to that DOM object.

Unfortunately I can't just put the code that assigns the onclick in document.Ready(), since the objects that it binds to are being created on the fly, long after document.Ready() has executed.

Does JQuery let you set up persistent bindings that will be automatically bound to a type of DOM object, even if it's generated on the fly?

+1  A: 

Have you looked a the jQuery plugin called LiveQuery?

From the LiveQuery documentation page:

For example you could use the following code to bind a click event to all A tags, even any A tags you might add via AJAX.

$('a') 
>     .livequery('click', function(event) { 
>         alert('clicked'); 
>         return false; 
>     });

Once you add new A tags to your document, Live Query will bind the click event and there is nothing else that needs to be called or done.

Ash
Is this different to the "live" function (posted below)?
jonathanconway
I think this might be a case of a great plugin being baked into the main library. I was not aware of live(), but yes it looks similar.
Ash
I think it's appropriate for it to be in-built functionality. Good stuff!
jonathanconway
@jonathanconway and @Ash the live() function in jquery 1.3 uses delegation whereas the livequery plugin using polling every 20ms or so. This makes the core implementation much, much, more efficient, but it has limitations; ie only some types of events are supported.
thomasrutter
+6  A: 

I think I've found the answer to my own question, right in the JQuery documentation, surprisingly enough.

http://docs.jquery.com/Events/live#typefn

live( type, fn )

Added in jQuery 1.3: Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.

jonathanconway