2

Based on this question, I have created a custom anonymous event listener as follows:

function init() {
    console.log("Initiating widgets");
}

window.addEventListener("widgetInit", init());

I can call it using $(window).trigger('widgetInit'); from code, however if I paste that into the console it simply returns the window object.

Is there a way to simulate the event via the console without modifying the code?

  • 3
    You meant to use `window.addEventListener("widgetInit", init);`. Or with jQuery: `$(window).on("widgetInit", init);` to make it actually work. – Bergi Aug 23 '17 at 19:40
  • Even with removing the parenthesis, I had to change the trigger to dispatchEvent as seen in @Michael Horn's answer. –  Aug 23 '17 at 20:12

3 Answers3

4

Perhaps you could try using the native DOM method:

window.dispatchEvent(new Event('widgetInit'));
Michael Horn
  • 3,819
  • 9
  • 22
1

It looks like jQuery is used is own event system for CustomEvent. If you use jQuery to listen to the event, it will work fine.

Otherwise, they are (less supported) way to create a CustomEvent: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

Axnyff
  • 9,213
  • 4
  • 33
  • 37
1

Your listener, I think, should be:

window.addEventListener("widgetInit", init);

So init without the parenthesis...

When you target a jQuery element by typing directly in the console, this element is alway returned. So the trigger worked... But I think your listener isn't working...

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
  • Even with removing the parenthesis (thanks), I had to change the trigger to `dispatchEvent` as seen in @Michael Horn's answer. –  Aug 23 '17 at 19:45