Triggering events in vanilla JavaScript

[2013-06-06] dom, dev, javascript, clientjs
(Ad, please don’t block)
So you want to trigger an event for a DOM element, without using jQuery? This blog post gives you a quick recipe for doing so.

The running example is about sending a submit event to a form. I needed to do that for a demo of user interface testing via CasperJS. And, unfortunately, the Form#submit method does not send that event on most web engines.

The recipe

Steps:
  1. Look up the constructor of the event, via a table on MDN that maps event names to event constructors.

    Example: submit events are created via the Event constructor.

  2. Look up the arguments of the event constructor, via the drafts of the specifications for DOM4 and UI Events.

    Example: The constructor for interface Event has the following Interface Definition Language (IDL) signature:

        Constructor(DOMString type, optional EventInit eventInitDict)
    
    Optionally, EventInit can be passed in as an object and configures whether an event bubbles or is cancelable. It is defined in IDL as:
        dictionary EventInit {
            boolean bubbles;
            boolean cancelable;
        };
    
  3. Dispatch the event. All event targets have a method dispatchEvent, whose only parameter is the event to dispatch.

    Example: The following code triggers a submit event:

        var elem = document.getElementById('myForm');
        var event = new Event('submit');  // (*)
        elem.dispatchEvent(event);
    
    Line (*) is equivalent to:
        var event = new Event(
            'submit',
            { bubbles: false, cancelable: false });
    
Update 2013-06-09: I’ve created a web page where you can check whether your browser supports DOM event constructors. A table shows how various browsers fare. The news is not good: Internet Explorer (up to and including version 10) does not provide support. Most other browsers do.

On browsers that don’t support event constructors, you have to resort to the legacy document.createEvent().