Hailwood
Hailwood

Reputation: 92651

watch for dom element creation?

So, basically I have a plugin that I want called on an element if it is created in the dom,

E.g. let's say I have a plugin called domWatch that runs the function if the specified selector gets created inside the selector it was called on.

so:

$('#container').domWatch('.mySelector', function(element){
    $(element).myPlugin();
});

$('#container').append($('<div />', {class: 'mySelector'})); //the new element should now have the myPlugin plugin called on it.

Is this possible to do?

Upvotes: 2

Views: 5057

Answers (5)

Uzair Farooq
Uzair Farooq

Reputation: 2437

You can use the arrive.js library that I developed for the exact same purpose (uses Mutation Observers internally). Usage:

$('#container').arrive('.mySelector', function(){
    $(this).myPlugin();
});

Upvotes: 6

Sorin Comanescu
Sorin Comanescu

Reputation: 4867

It looks like a job for the delegated form of the .on() event:

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

Upvotes: 0

Holf
Holf

Reputation: 6441

Sounds a lot like Live Query. Although this does involve continuous polling which does have a performance hit.

Here are some demos.

Upvotes: 1

kioopi
kioopi

Reputation: 2250

If you are targeting very modern browsers only you could check out MutationObserver, which is designed for that objective.

https://developer.mozilla.org/en-US/docs/DOM/MutationObserver

Upvotes: 1

Nicolas R
Nicolas R

Reputation: 1011

Have a look at this clever hack: http://www.backalleycoder.com/2012/04/25/i-want-a-damnodeinserted/. It uses CSS3 animations to detect when an element was inserted into the DOM.

The problem with 'listening for when a DOM element is created' is the performance hit, so maybe you should consider a different approach to solve your problem.

I'm sure there are many, way simpler ways to achieve your goal.

Upvotes: 3

Related Questions