I load content into a div
at some point dynamically, from my main page script:
$(function() {
$('#myDiv').load('layer2.html');
}
Then, I want to receive custom events sent by layer2.html
's corresponding script on the main page script. If I add this on the main one:
$(document).on('event1', function () {
window.alert('event1 received');
});
And the following in the layer2.html
script:
var event = new Event('event1');
document.dispatchEvent(event);
It works (the alert shows). Note that above isn't jQuery. But triggering the event with jQuery instead as the way below:
$(document).trigger('event1');
Does not work, even when I apply the following change in an attempt to succeed on event delegation system, which from my previous readings I understand that is what my case is all about:
$(document).on('event1', '#myDiv', function() {
window.alert('event1 received');
});
Finally, I want to note I found similar questions but they only dealed with click
events or other native ones, rather than custom events.
How to fix my issue using jQuery and event delegation?