Using jQuery To Bind And Trigger Event Handlers On Detached DOM Nodes
Often times, we use jQuery to bind event handlers to DOM nodes that are children of the current document tree. When we do this, jQuery stores the event handlers in the given node's "events" collection. These bindings remain in place until they are explicitly unbound or until the DOM nodes are removed from the document (NOTE: Using .detach() does not unbind event handlers). Because of this fact, I think it is tempting to believe that detached DOM nodes can't react to events; but, in fact, the opposite is true - jQuery can both bind and triggered events on nodes that are not part of the currently rendered document.
As you can see, we are creating a detached DIV node. Then, we are binding the custom event, "ping," to that node with some bind-time data. Once the event handler is bound, I am then using jQuery to programmatically trigger the event, all while it is detached from the document.
As a sort of control-case, I am also attaching and removing the node to and from the Body element in order to confirm that remove() still clears all bound data (including the "events" collection). When I run the above code, I get the following console output:
As you can see, both the event binding and the event triggering executed successfully while our DIV remained detached from the current document tree. And, just as we have seen previously, attaching and then detaching the DIV resulted in a loss of event binding.
It might seem odd to care about event binding outside the context of the current document tree; but, I have some ideas that I want to play with that leverage this very behavior. More to come on that later.
Want to use code from this post? Check out the license.
very cool, i knew this was normal, but never really thought of using it for something useful, you got me thinking tho! look forward to seeing what you come up with!
You have me a little curious as to what benefits having an element not attached to the DOM will bring too.
My guess is, you're going to create a div and attach web socket or web worker events to it, so that the div itself can interactively build its own contents, prior to attaching itself to the DOM to display its contents.
I'll bet that kind of encapsulation appeals to you. :-)
Interesting idea with the WebSockets.