Jonathan
Jonathan

Reputation: 32868

JQuery - making code execute for each new DOM object instantiated

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?

Upvotes: 1

Views: 2567

Answers (4)

Tim Ogilvy
Tim Ogilvy

Reputation: 1973

This used to be covered by 'live', 'delegate', or sometimes 'bind'. These are now replaced with 'on' however there are some caveats as discussed here: Javascript event binding persistence

Upvotes: 0

Adam
Adam

Reputation: 28858

Not possible in jQuery core (as you've probably realized with other answers referring to some plugins)... this can be a very simple task if you dont necessarily need all the functionality of something like livequery

For the browsers that support them - use the DOM level 2 event - 'DOMNodeInserted':

http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-mutationevents

Upvotes: 0

Jonathan
Jonathan

Reputation: 32868

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.

Upvotes: 8

Ash
Ash

Reputation: 62096

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.

Upvotes: 1

Related Questions