Partager via


Creating and firing synthetic events

When creating and firing synthetic events, the createEvent()/BindEvent() pattern has been deprecated and the DOM L4 event constructor pattern using new Event() is recommended.

History

Support for standardized synthetic events began in Windows Internet Explorer 9. The constructor pattern for a synthetic event required a two step process.

First you would use the createEvent() method to create an event object of a specific type, then an initEvent() method to initialize it. There is a generic initEvent(), then 23 specialized variations for different types of event objects. For example, the following code creates a synthetic MouseEvent, uses a initMouseEvent() to initialize it as a click, and fires it on a checkbox element:

var mycheckbox = document.getElementById('mycheckbox');
var clicker = document.createEvent("MouseEvents");
clicker.initMouseEvent("click",true,true,"window",0,0,0,0,0,false,false,false,false,0,null);    
mycheckbox.dispatchEvent(clicker);

New syntax

With the DOM L4 event constructor pattern, you create a new event.

var mycheckbox = document.getElementById('mycheckbox');
var clicker = new MouseEvent("click", {
  'bubbles': true,
  'cancelable': true,
  'view': window,
  'detail': 0,
  'screenX': 0,
  'screenY': 0,
  'clientX': 0,
  'clientY': 0,
  'ctrlKey': false,
  'altKey': false,
  'shiftKey': false,
  'metaKey': false,
  'button': 0,
  'relatedTarget': null
});
mycheckbox.dispatchEvent(clicker);

The first parameter is an event type and the second parameter is an optional dictionary of event properties. The most common are bubbles and cancelable, but for different events you can add event-specific properties, such as clientX and clientY for a MouseEvent. In the optional dictionary, we duplicate the last 14 parameters of the initMouseEvent(), but instead of a confusing sequence of numbers and booleans you have to refer to docs to make sure you're getting in the right order, the dictionary makes the code much more readable and maintainable.

Note  Although deprecated, the createEvent()/initEvent() syntax remains functional at this time to support backward compatibility.

 

Feature testing

To test for support for the DOM L4 event constructor pattern in Microsoft Edge:

if (typeof window.Event == "function"){
  // use new syntax
} else {
  // use old syntax
}