With jQuery, there’s no event to subscribe to when you want to know when an element is removed from the DOM.
But that doesn’t mean you’ll never need that. Actually, it can come in handy for a lot of things, such as when you’re using tooltips.
When your mouse enters an element, you’ll make a little tooltip pop-up above the element to show more informations; and when your mouse leaves that element, the tooltip will disappear.
Now, what happens if you delete that element while the tooltip is visible? The element will disappear, but no « mouseleave » event will be triggered, even if you move your mouse, because the element doesn’t exist anymore, so how could your mouse leave it?
So what’s the trick? Easy: subscribe to the remove event on that element.
$("#element").bind("remove", function(){ $("#tooltip").remove(); });
But wait, there’s no such thing as a remove event in jQuery! Well, let’s create it then!
To avoid having to rewrite a lot of code, thus to avoid having to use a different function than .remove(), we’re just going to override it.
We’re first storing the original jQuery .remove() function, located in $.fn, the object that stores every jQuery function.
var original_remove = $.fn.remove;
Now that it’s stored, we can override it to customize its behavior.
$.fn.remove = function(){ $(this).trigger("remove"); original_remove.apply($(this)); };
So, how is .remove() behaving now?
The first line simply triggers the remove event on the object that we’re going to remove. That way, we can subscribe to it like we did at the beginning, and it will work.
The second line calls the original .remove() function we stored earlier. The JavaScript .apply() function allows us to execute a function while passing it a context ($(this), the object .remove() has been executed on).
Let’s review the whole code:
// override the .remove() function var original_remove = $.fn.remove; $.fn.remove = function(){ $(this).trigger("remove"); original_remove.apply($(this)); }; // bind something to the remove event on an element $("#element").bind("remove", function(){ $("#tooltip").remove(); }); // remove that element $("#element").remove(); // will call the custom .remove() function, thus triggering the above bound function
That’s a quick and easy way to add a custom behavior to a jQuery function, while keeping the original one!