简体   繁体   中英

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/>');
    $control.onAppend(function(){
        $(this).applyCustomScrollBar();
    });

    return $control;
}

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'
}).appendTo("body").trigger("appened");​

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

Hope it helps

You can do that without jquery with MutationObserver

MutationObserver provides developers a way to react to changes in a DOM. It is designed as a replacement for Mutation Events defined in the DOM3 Events specification.

// select the target node
var target = document.getElementById('some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
observer.disconnect();

source : devdocs.io that took it from This blog post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM