-1

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?

j08691
  • 204,283
  • 31
  • 260
  • 272
Adrián
  • 45
  • 1
  • 3
  • 12
  • you don't need event delegation here, the document isn't a dynamic element. – Kevin B May 17 '18 at 19:54
  • 1
    I can't recreate your problem. Triggering works both immediately, and after a delay. https://jsfiddle.net/9g1v6wrb/ – Kevin B May 17 '18 at 19:56

1 Answers1

0

I am sorry for your time, my problem was that I was including jQuery again on the included file (layer1.html), possibly resulting in two unrelated jQuery instances, with different events storage. Making sure jQuery is included only on the main file allows me to use easy triggers again. Thanks!

Adrián
  • 45
  • 1
  • 3
  • 12