0

I am using jQuery's .on() function to attach event handlers to elements when they appear in the document:

$(document).on('change', '#elementId', handlerFunction);

I would also like to call the handlerFunction when the element becomes part of the document, not just when the change event is triggered. Is there an event that I can add to the list?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sonny
  • 8,204
  • 7
  • 63
  • 134
  • Couldn't you call the function ina callback of the code that adds elements to the document? – j08691 Sep 05 '12 at 16:28
  • You can use `Mutation Events` but they are deprecated. http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInserted – Ram Sep 05 '12 at 16:30
  • There's an OnDOMNodeInserted event that can be used for this, but it's not cross browser. – adeneo Sep 05 '12 at 16:30
  • @j08691 - That makes sense, but I can't add a callback there. – Sonny Sep 05 '12 at 16:43
  • See this http://stackoverflow.com/questions/7434685/event-when-element-added-to-page – Nal Sep 05 '12 at 17:23

2 Answers2

0

in your handler function add this line

$('#elementId').trigger('change');
Ashirvad
  • 2,367
  • 1
  • 16
  • 20
  • I can't trigger the event on a non-existent element. I want a listener that captures the event of the element being added to the document. – Sonny Sep 05 '12 at 16:45
0

You may use the load() function of jQuery:

$('#elementId').load(handlerFunction);

To paraphrase jQuery's website:

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.

JoeLinux
  • 4,198
  • 1
  • 29
  • 31
  • The element can be loaded some time after the document is loaded, which is why I am using `$(document).on()`. – Sonny Sep 05 '12 at 16:44