views:

114

answers:

3

I would like to run some code right after a certain set of elements are attached. jQuery.live() allows you to bind event handlers to elements, even if they are created later. But AFAIK there is no suitable method to do something like the following:

$("some selector").live("attach", function() { $(this).whatever(); });

How can I accomplish this?

EDIT: For clarification; I would like to run an animation on a newly created element. Aside from the fact animating is useless before appending first, in some browsers backgroundColor property isn't inherited from the CSS class until it's attached to DOM. This causes my animation code to break.

So I would like to create this element, somehow apply the animation to run once it's attached and then return it.

A: 

AFAIK there are no events in jQuery that are fired when the dom changes. You would need to run code on the newly attached element which becomes fully queryable as soon as it is passed to jquery eg

var $span = $('<span>my new document fragment</span>');
$span.css('what','ever');

$('div').append($span);
James Westgate
I have added some details about my problem. What you describe is normally what I am doing. But in this case, `backgroundColor` isn't set (from the class) until the element is attached to DOM.
muhuk
+1  A: 

I suggest you check out DOMNodeInserted and DOMNodeRemoved.

This might be useful as well: Detecting When DOM Elements Have Been Removed With jQuery

Makram Saleh
+1  A: 

Very difficult to do in a cross-browser compatible way. I've had to implement a similar thing, and needed to use the mutation events as @Makram has suggested (DOMNodeInserted, DOMNodeRemoved), and a setInterval fallback method (simply polling for changes) - the setInterval is stopped if one of the mutation events is fired, as then you can assume the events work and you don't need the polling.

Also of note is that live() didn't seem to always work in IE, so I'm manually re-binding events in some circumstances (after unbinding first of course!)

Graza