JQuery Event Tracking

in some function, I remove an element like this $('#'+id+' img.load').remove(); How can I track this event and run my own code?

+4
source share
2 answers
 (function($){ var remove_orig = $.fn.remove; $.fn.remove = function(){ console.log('Remove called'); remove_orig.apply(this, arguments); }; })(jQuery); 

You can β€œconnect” to any jQuery function and put your own processing code inside (including the logging method), which will be executed before the jQuery native code is executed.

demo (another version with selector shown)


Catching deletion is easy using the above overload. Just change the binding to trigger the trigger before (or after) jQuery:

 (function($){ var remove_orig = $.fn.remove; $.fn.remove = function(){ this.trigger('removing'); remove_orig.apply(this, arguments); }; })(jQuery); $('#foo').bind('removing',function(e){ alert('#foo is being removed'); }); $('#foo').remove(); 
+5
source

One way is to β€œtrigger” a custom event (in this example, I use a window):

 $('#'+id+' img.load').remove(); $(window).trigger("MyElementRemoved", [id]); 

Then, in another part of your code, "handle" the event:

 $(window).bind("MyElementRemoved", function(e, elementId) { alert("element removed: " + elementId); } 
+3
source

All Articles