0

I am looking for a pretty way to handle an append/remove event from an element, other than manually triggering an event or something of sorts.

Something like this would be amazing:

$('#id').on("append", function() { ... }

Thanks in advance!

Cosme Benito
  • 125
  • 2
  • 13
  • The accepted response is pretty interesting but I have been unable to make it work for the remove event, care to assist me on that? :) – Cosme Benito Jun 29 '13 at 00:40

1 Answers1

1

As said in the comments, you can trigger an append function with that:

(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>");

This code was taken from this answer : https://stackoverflow.com/a/7167210/2324107

But since remove is a little bit different because without any arguments, you will want to target the parent of the element. I modified a little bit the code before and got this result :

var origRemove = $.fn.remove;

$.fn.remove = function () {
    if(arguments.length){
        return origRemove.apply(this, arguments).trigger("remove");
    }else{
        var $parent = this.parent();
        console.log(this)
        origRemove.apply(this, arguments);
        $parent.trigger('remove');
        return this
    }
};

If there is an argument, it will trigger on the selected element. Example, $('body').remove('div'); will trigger remove event on the body. But if you write $('div').remove();, it will trigger on the parent of the div.

I made a fiddle, take a look : http://jsfiddle.net/ZxdU3/

The event listener will be append and remove. It will not trigger is you use any other DOM insertion function (after, before or even appendTo).

Community
  • 1
  • 1
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75