You can use event bubbling to listen to the events on document
, and based on the target element, execute appropriate event handling logic.
jQuery makes it easier to register such event handlers by simplifying the logic around identification of the target element. The syntax for registering such an event handler would be: $(document).on(events, selector, handler)
.
These are called Delegated Event Handlers in jQuery's documentation:
Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
I have illustrated an example in the snippet below. Notice how you do not need to re-register the event listener even after replacing the HTML content.
$(document).on("click", "#clickMe", function() {
alert("Element clicked.");
});
// Change the innerHTML after 10 seconds.
setTimeout(function() {
$(document.body).html(`
<div id="clickMe">[New] Click Me</div>
`);
}, 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="clickMe">Click me</div>
You can read more about event bubbling here and more about jQuery's event handling syntax here.
Note: In my opinion, you need to rethink your architecture. While the suggested approach works, given the unconventional nature of your architecture, you may run across other challenges in future.