element.dispatchEvent

Table of contents

  1. 1. Summary
  2. 2. Syntax
  3. 3. Example
  4. 4. Notes
  5. 5. Specification
Table of contents
  1. 1. Summary
  2. 2. Syntax
  3. 3. Example
  4. 4. Notes
  5. 5. Specification

« Gecko DOM Reference

Summary

Dispatches an event into the event system. The event is subject to the same capturing and bubbling behavior as directly dispatched events.

Syntax

bool = element.dispatchEvent(event)
  • element is the target of the event.
  • event is an event object to be dispatched.
  • The return value is false if at least one of the event handlers which handled this event called preventDefault. Otherwise it returns true.

Example

This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods. You can view the example in action here.

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var cb = document.getElementById("checkbox"); 
  var canceled = !cb.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

 

 

To read an example of triggering a custom event, see Creating and triggering custom events

Notes

As demonstrated in the above example, dispatchEvent is the last step of the create-init-dispatch process, which is used for dispatching events into the implementation's event model.

The event can be created using document.createEvent method and initialized using initEvent or other, more specific, initialization methods, such as initMouseEvent or initUIEvent.

See also the Event object reference.

Tags (3)

Edit tags

Attachments (0)

 

Attach file