views:

170

answers:

5

I'm working with a third-party product. It uses JavaScript (non-JQuery) code on the page to generate DOM elements on the fly.

Is it possible to run a jQuery script whenever this third-party code generates a DOM element matching a given selector?

To explain in another way, I don't want to try and integrate with that code. I just want to watch for certain elements to be created, which is the cue to run my own custom jQuery.

+1  A: 

There are the so-called DOM mutation events. I'm not sure how well they're supported across browsers, though, since I still haven't had the chance to use them. They're not even listed in ppk's compatibility tables.

Reinis I.
DOM mutation events will be awesome once it's implemented, but sadly it's not supported in Opera, IE or FF2.
fudgey
A: 

Based on the jquery documentation, it sounds like load() can be used on any element, not just window/document type elements. So if you know what the elements will be (the id, the class), you could just have the jquery bind to those selectors with load() and do what it is you need done.

Anthony
+1  A: 

Depending on what browsers you need to support, you may be able to use the DOM mutation events which Reinis refers to.

Here's an online resource for testing your target browser(s): http://www.gtalbot.org/DHTMLSection/DOM2MutationEvents.html

If these events are not supported in your target browsers, the only alternative I can think of is to poll the contents of whatever node would contain the new elements.

jhurshman
IE and Firefox. Doesn't look like IE (with version 8) works.
Alex Angas
+5  A: 

Barring the DOM mutation events that Reinis mentions, I can think of three options:

1) If you are wanting to simply have event handling on the new elements, you can use jQuery Live

2) You can use setTimeout to periodically inspect the DOM for new elements.

3) If you feel like diving into the third party code (for understanding, not direct modification), you can then provide a functional override that notifies you, explicitly, when their function executes

var oldFunc = thirdParty.theirFunc;
thirdParty.theirFunc = function(){ 
    oldFunc();

    // alert myself of the change.
    myDomChangedFunction();
};

This way you aren't actually modifying their source directly, just functionally :)

Matt
Number 3 is what I think I'll try - thanks!
Alex Angas
@Matt - Would `onload()` not work?
Anthony
@Anthony - I honestly don't know :). I've never seen what you proposed in your load() solution. Are you suggesting that onload() is fired everytime the browser finishes loading elements? (such as initial page load, or when it finishes loading new elements into the DOM from an AJAX call)
Matt
A: 

check out jQuery's "live" event bindings, it might help: http://docs.jquery.com/Events/live

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.

csulok