Is it possible to add some kind of an event/handler when an element is appended to the DOM...?
.click(), .change(), .keyup() etc. alike...
I need to get the height of an element as soon as it is appended and then set the height to another element
Is it possible to add some kind of an event/handler when an element is appended to the DOM...?
.click(), .change(), .keyup() etc. alike...
I need to get the height of an element as soon as it is appended and then set the height to another element
You can override the default append method and cause it to trigger a custom append event. Then bind a handler to an element for that event: http://jsfiddle.net/H8ygx/
(function($) {
var origAppend = $.fn.append;
$.fn.append = function () {
return origAppend.apply(this, arguments).trigger("append");
};
})(jQuery);
$("div").bind("append", function() { alert('Hello, world!'); });
$("div").append("<span>");
For that you can use the "DOMSubtreeModified" event. But it has limited compatibility. See: http://www.quirksmode.org/dom/events/#t18
$('#myDiv').live("DOMSubtreeModified", function() {
alert('something changed inside #myDiv div');
});
This event handler will work with all standard DOM modifying methods: appendTo(), insertBefore(), insertAfter(), etc.
The accepted answer will trigger the event on the container to which you are appending, which may not be what you want. Here is a version that will trigger the event on the element(s) you are appending. Note that this still doesn't correctly handle a function input to append().
(function($)
{
var jqAppend = $.fn.append;
$.fn.append = function()
{
// Make a list of arguments that are jQuery objects
var appendages = $.makeArray(arguments).filter(function(arg)
{
return arg instanceof $;
});
// Call the actual function
var returnValue = jqAppend.apply(this, arguments);
// Trigger "append" event on all jQuery objects that were appended
for (var i = 0; i < appendages.length; ++i)
{
appendages[i].trigger('append');
}
return returnValue;
};
})(jQuery)
As suggested by Scherbius.com, you can use .on("DOMSubtreeModified")
but I suggest to apply it to the parent element (which should be known to you if you are appending to it):
<div id="parent"></div>
<script>
$('<div id="child"></div>').appendTo("#parent");
//Heres what you asked about:
$("#parent).on("DOMSubtreeModified", function(){console.log("Do something!")})
</script>
One way is that if you are doing append yourself make a function like:
function do_append(elem)
{
elem.append('......');
// get height of your element
// set height of another element
}
or tell me if this method doesn't cut it for you :)