Search code examples
javascriptdom-events

Trigger (dispatchEvent) the 'onerror' with javascript?


In my code I did: element.onerror = my_function;

I am wondering how to forcefully trigger this event so I can test it?

Can someone show me how to use the dispatchEvent flow to do this?


Solution

  • OKAY I figured it out!

    var evt = document.createEvent('HTMLEvents');
    evt.initEvent('error', false, false);
    element.dispatchEvent(evt);
    

    I figured out that onerror is an 'HTMLEvents' according to google. Since the event name is error, the event is error, and I knew that error doesn't bubble, hence the false in the second parameter of initEvent.