Adding custom events to jQuery-Functions

Today I had to execute a function everytime I appended content to an HTML-Document. Easy thing, you’d say: Add the function right after appending the stuff to the DOM…

But that’s coupling the function far too tight to that code. I need to make sure that the function is executed every time the document is altered. And forgetting to call that function on at least one place is easy 😉

So wouldn’t it be easier to use the DOMChange-Event? Well… Looks like that’s not that easy and doesn’t work in all browsers I need.

But using an event is a great idea. Add an event listener to the document once and trigger a custom event on every change. Sounds like a plan! Though: Adding the trigger of the custom event to every place where the DOM can be changed is as error prone as adding the function call…

So how can one solve that? Especially when all the DOM manipulations are done via jQuery? Wouldn’t it be cool to trigger the event every time I call the append or prepend-function?

Oh wait!

Looks like that’s a good idea! Overwrite the jQuery-functions with a self-defined function that triggers the event and also executes the original action. And there was even a StackOverflow-Question that shows how to do that: Easy to be adapted.

So here is what I finally came up with:

var oAppend = jQuery.fn.append;
jQuery.fn.append = function() {
    var f = oAppend.apply(this, arguments);
    return f;

First store the original implementation, then overwrite it and within the new function call the original implementation.

No I can use the event like this:

$('body').on('org_heigl:afterAppend', function(){ 
    /* Do whatever you want */

Or did I miss something?

 architectural daughtsman, brother, developer, father, husband, master of forestry sciences, scout

One thought on “Adding custom events to jQuery-Functions

Leave a Reply

Your email address will not be published. Required fields are marked *