The post Inserting & Triggering Custom Events In jQuery Functions appeared first on Justin Silver.
]]>I recently had the need to detect when new elements were appended to the DOM, however by default in jQuery there is no “append” event. This meant that the code I wanted to write, was invalid.
(function($) {
$(document).on('append', function(){
// handle the "append" event using the elements from the arguments
});
})(jQuery);
The solution I ended up using involved caching the existing jQuery.append() to jQuery._append() and then overriding jQuery.append() to call the cached function internally, followed by the triggering of my new “append” event.
(function($) {
// store a copy of the append() function as _append()
$.fn._append = $.fn.append;
// overwrite the existing append()
$.fn.append = function () {
return $.fn
// apply the cached (function)ality using _append()
._append.apply(this, arguments)
// trigger our custom "append" event to fire handlers.
.trigger("append", [arguments]);
};
})(jQuery);
The post Inserting & Triggering Custom Events In jQuery Functions appeared first on Justin Silver.
]]>