pickhunter pickhunter - 1 year ago 94
HTML Question

Fire OnAppend event for jQuery element when it gets appended to the DOM

I wrote some code to generate custom controls. The code returns a jQuery element and the caller appends this jQuery element to the DOM.
I apply a custom scrollbar to the control in the generator code, but it doesn't get applied as the element has not been appended to the DOM yet.

My question: Is there any onAppend event or something like that, so that I apply the custom scrollbar at the time when the element has been appended to the DOM?

Sample code for generator:

function getControl(controlParams){
var $control = $('<div/>');
$control.applyCustomScrollBar(); //Not appended to DOM yet, so doesnt work
return $control;

Sample code for consumer:

var $control = getControl(controlParams);
$("body").append($control); //Appending to DOM now

Want to do something like:

function getControl(controlParams){
var $control = $('<div/>');

return $control;

Answer Source

To detect if element has been added to the DOM, you need to trigger a custom event, try this:

$("body").on("appened", "div", function(event){
    //event after append the element into DOM, do anything
    $(this).css("background", "blue");

$("<div/>", {
    id: "some-control",
    text: 'Example Control'

Fiddle example: http://jsfiddle.net/uudDj/1/

Hope it helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download