views:

398

answers:

3

To be clear: I am not asking how to put existing hooks onto new DOM elements. I know about the live() function and the old livequery plugin. I am asking something else.

What I want to know is how to hook onto the very creation of new DOM elements. The reason I'm asking is I'm creating a third-party user JS script that doesn't have control over first-party scripts. Those first-party scripts (which are obfuscated) update the page periodically by adding new DOM elements. I want to execute code after those elements are added.

Using $( '...' ).bind( 'ajaxSuccess', function() ..... ) works for some additions, but not all of them.

A: 

I'm not sure why you ask if you know about livequery. Livequery will allow you to hook into arbitrary new DOM elements. Outside of this, the only thing I know to do is hook into the DOM methods (such as appendChild etc...)

The live() function which was integrated into jQuery actually isn't the full livequery implementation. (Resig thought it was too much functionality to be integrated without blowing the code size up too far)

In live(), what is missing is the following type function:

$('*').livequery(function() {
 // do something
});

Use this, and it should catch any additions.

altCognito
Can you expand on that? Is there livequery functionality that goes beyond the new 1.3 live() function?
Pistos
Updated with an example.
altCognito
live() doesn't allow arbitrary selectors (yet). That's the main limitation. There are also some lifecycle concerns; they're all in the jquery 1.3 release notes.
DDaviesBrackett
Yeah, precisely my point, I updated the example which said used live as the function. *rolls eyes at self* It's been a long day.
altCognito
+2  A: 

If they are always being added with the document.createElement method you could simply replace it and do your tracking in there.

document.replacedCreateElement = document.createElement;
document.createElement = function(tagName) {
    this.replacedCreateElement(tagName);
    //do your tracking 
}
Doomspork
Interesting! I didn't know we could just alias/override core functions like that.
Pistos
This is exactly what livequery does.
altCognito
When I tried this, the browser(s) shoot up in CPU usage. I guess it's too much DOM spidering.
Pistos
+1  A: 

Well, I went with this pair, which seems to fire on the desired DOM updates within 20 seconds or less:

$( '#someid' ).bind( 'ajaxSuccess', function() { ... } );
$( '#someid' ).ajaxSuccess( function( e, r, s ) { ... } );

I'd rather not have to slow page loading by depending on livequery, and the replacedCreateElement solution thrashed the CPU.

Pistos