Document.createEvent() - Web API Interfaces | MDN

archived 21 Jun 2015 08:37:48 UTC
Your Search Results

    Document.createEvent()

    Many methods used with createEvent, such as initCustomEvent, are deprecated. Use event constructors instead.
     
    Creates an event of the type specified. The returned object should be first initialized and can then be passed to element.dispatchEvent.

    Syntax

    var event = document.createEvent(type);
    
    • event is the created Event object.
    • type is a string that represents the type of event to be created. Possible event types include "UIEvents", "MouseEvents", "MutationEvents", and "HTMLEvents". See Notes section for details.

    Example

    This article demonstrates how to create and dispatch events.

    Creating custom events

    Events can be created with the Event constructor as follows:
    var event = new Event('build');
    
    // Listen for the event.
    elem.addEventListener('build', function (e) { ... }, false);
    
    // Dispatch the event.
    elem.dispatchEvent(event);
    This constructor is supported in most modern browsers (with Internet Explorer being the exception). For a more verbose approach, see the old-fashioned way below.

    Adding custom data – CustomEvent()

    To add more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data.
    For example, the event could be created as follows:
    var event = new CustomEvent('build', { 'detail': elem.dataset.time });
    This will then allow you to access the additional data in the event listener:
    function eventHandler(e) {
      log('The time is: ' + e.detail);
    }

    The old-fashioned way

    The older approach to creating events uses APIs inspired by Java. The following shows an example:
    // Create the event.
    var event = document.createEvent('Event');
    
    // Define that the event name is 'build'.
    event.initEvent('build', true, true);
    
    // Listen for the event.
    document.addEventListener('build', function (e) {
      // e.target matches document from above
    }, false);
    
    // target can be any Element or other EventTarget.
    document.dispatchEvent(event);

    Triggering built-in events

    This example demonstrates simulating a click (that is programmatically generating a click event) on a checkbox using DOM methods. View the example in action.
    function simulateClick() {
      var event = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true
      });
      var cb = document.getElementById('checkbox'); 
      var canceled = !cb.dispatchEvent(event);
      if (canceled) {
        // A handler called preventDefault.
        alert("canceled");
      } else {
        // None of the handlers called preventDefault.
        alert("not canceled");
      }
    }

    Browser compatibility

     

    Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
    Event() constructor 15 11 Not supported 11.60 6
    Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
    Basic support ? ? ? ? 6

    See also

    Notes

    Event type strings suitable for passing to createEvent are defined in event modules. Some event modules are defined in DOM Events specifications, some modules are defined in other specification (such as SVG), and some event types are Gecko-specific. See the table below for details.
    To-do: add event names to the table too.
    Event Module Event type to pass to createEvent Method to be used to initialize the event
    DOM Level 2 Events
    User Interface event module "UIEvents" event.initUIEvent
    Mouse event module "MouseEvents" event.initMouseEvent
    Mutation event module "MutationEvents" event.initMutationEvent
    HTML event module "HTMLEvents" event.initEvent
    DOM Level 3 Events
    User Interface event module "UIEvent", "UIEvents" event.initUIEvent
    Mouse event module "MouseEvent", "MouseEvents" event.initMouseEvent
    Mutation event module "MutationEvent", "MutationEvents" event.initMutationEvent
    Mutation name event module (not implemented in Gecko as of June 2006) "MutationNameEvent" event.initMutationNameEvent
    Text event module "TextEvent" (Gecko also supports "TextEvents") event.initTextEvent (not implemented)
    Keyboard event module "KeyboardEvent" (Gecko also supports "KeyEvents") event.initKeyEvent (Gecko-specific; the DOM 3 Events working draft uses initKeyboardEvent instead)
    Custom event module "CustomEvent" event.initCustomEvent
    Basic events module "Event" (Gecko also supports "Events") event.initEvent
    SVG 1.1 Scripting
    SVG "SVGEvents" (Gecko also supports "SVGEvent") event.initEvent
    "SVGZoomEvents" (Gecko also supports "SVGZoomEvent") event.initUIEvent
    Other event types supported by Gecko
    - "MessageEvent" event.initMessageEvent
    "MouseScrollEvents", "PopupEvents" event.initMouseEvent
    "PopupBlockedEvents" event.initPopupBlockedEvent
    "XULCommandEvent", "XULCommandEvents" event.initCommandEvent
    Progress Events "ProgressEvent" ProgressEvent.initProgressEvent()Deprecated since Gecko 22.0
    Animation Events "AnimationEvent" (or "WebKitAnimationEvent" for WebKit/Blink-based browsers) AnimationEvent.initAnimationEvent()Deprecated since Gecko 23.0
    Transition Events "TransitionEvent" (or "WebKitTransitionEvent" for WebKit/Blink-based browsers) TransitionEvent.initTransitionEvent()Deprecated since Gecko 23.0
    The reason some events can be created using any of two event type strings is that DOM Level 3 Events changed the event type strings to be singular, while still supporting older plural names for backwards-compatibility.

    Specification

    Document Tags and Contributors

    Last updated by: teoli,
    Hide Sidebar
    See also
    1. Document
    2. Properties
      1. Document.URL
      2. Document.activeElement
      3. Document.alinkColor
      4. Document.anchors
      5. Document.applets
      6. Document.async
      7. Document.bgColor
      8. Document.body
      9. Document.characterSet
      10. Document.compatMode
      11. Document.contentType
      12. Document.currentScript
      13. Document.defaultView
      14. Document.designMode
      15. Document.dir
      16. Document.doctype
      17. Document.documentElement
      18. Document.documentURI
      19. Document.documentURIObject
      20. Document.domConfig
      21. Document.domain
      22. Document.embeds
      23. Document.fgColor
      24. Document.forms
      25. Document.head
      26. Document.height
      27. Document.images
      28. Document.implementation
      29. Document.inputEncoding
      30. Document.lastModified
      31. Document.lastStyleSheetSet
      32. Document.linkColor
      33. Document.links
      34. Document.location
      35. Document.mozFullScreen
      36. Document.mozFullScreenElement
      37. Document.mozFullScreenEnabled
      38. Document.mozSyntheticDocument
      39. GlobalEventHandlers.onabort
      40. Document.onafterscriptexecute
      41. Document.onbeforescriptexecute
      42. GlobalEventHandlers.onblur
      43. GlobalEventHandlers.onchange
      44. GlobalEventHandlers.onclick
      45. GlobalEventHandlers.onclose
      46. GlobalEventHandlers.oncontextmenu
      47. GlobalEventHandlers.ondblclick
      48. GlobalEventHandlers.onerror
      49. GlobalEventHandlers.onfocus
      50. GlobalEventHandlers.oninput
      51. GlobalEventHandlers.onkeydown
      52. GlobalEventHandlers.onkeypress
      53. GlobalEventHandlers.onkeyup
      54. GlobalEventHandlers.onload
      55. GlobalEventHandlers.onmousedown
      56. GlobalEventHandlers.onmousemove
      57. GlobalEventHandlers.onmouseout
      58. GlobalEventHandlers.onmouseover
      59. GlobalEventHandlers.onmouseup
      60. Document.onoffline
      61. Document.ononline
      62. GlobalEventHandlers.onscroll
      63. GlobalEventHandlers.onselect
      64. GlobalEventHandlers.onsubmit
      65. Document.origin
      66. Document.plugins
      67. Document.pointerLockElement
      68. Document.popupNode
      69. Document.preferredStyleSheetSet
      70. Document.readyState
      71. Document.referrer
      72. Document.scripts
      73. Document.selectedStyleSheetSet
      74. Document.styleSheetSets
      75. Document.styleSheets
      76. Document.title
      77. Document.tooltipNode
      78. Document.vlinkColor
      79. Document.width
      80. Document.xmlEncoding
      81. Document.xmlVersion
    3. Methods
      1. Document.adoptNode()
      2. Document.caretPositionFromPoint()
      3. Document.clear()
      4. Document.close()
      5. Document.createAttribute()
      6. Document.createCDATASection()
      7. Document.createComment()
      8. Document.createDocumentFragment()
      9. Document.createElement()
      10. Document.createElementNS()
      11. Document.createEntityReference()
      12. Document.createEvent()
      13. Document.createExpression()
      14. Document.createNSResolver()
      15. Document.createNodeIterator()
      16. Document.createProcessingInstruction()
      17. Document.createRange()
      18. Document.createTextNode()
      19. Document.createTouch()
      20. Document.createTouchList()
      21. Document.createTreeWalker()
      22. Document.elementFromPoint()
      23. Document.enableStyleSheetsForSet()
      24. Document.evaluate()
      25. Document.execCommand()
      26. Document.exitPointerLock()
      27. Document.getBoxObjectFor()
      28. Document.getElementById()
      29. Document.getElementsByClassName()
      30. Document.getElementsByName()
      31. Document.getElementsByTagName()
      32. Document.getElementsByTagNameNS()
      33. Document.getSelection()
      34. Document.hasFocus()
      35. Document.importNode()
      36. Document.loadOverlay()
      37. Document.mozCancelFullScreen()
      38. Document.mozSetImageElement()
      39. Document.open()
      40. Document.queryCommandSupported()
      41. Document.querySelector()
      42. Document.querySelectorAll()
      43. Document.registerElement()
      44. Document.releaseCapture()
      45. Document.write()
      46. Document.writeln()
    4. Inheritance:
      1. Node
      2. EventTarget
    5. Related pages:
      1. Attr
      2. CDATASection
      3. CharacterData
      4. ChildNode
      5. Comment
      6. CustomEvent
      7. DOMConfiguration
      8. DOMError
      9. DOMErrorHandler
      10. DOMException
      11. DOMImplementation
      12. DOMImplementationList
      13. DOMImplementationRegistry
      14. DOMImplementationSource
      15. DOMLocator
      16. DOMObject
      17. DOMString
      18. DOMTimeStamp
      19. DOMTokenList
      20. DOMUserData
      21. DocumentFragment
      22. DocumentType
      23. Element
      24. ElementTraversal
      25. Entity
      26. EntityReference
      27. Event
      28. EventTarget
      29. HTMLCollection
      30. MutationObserver
      31. Node
      32. NodeFilter
      33. NodeIterator
      34. NodeList
      35. NonDocumentTypeChildNode
      36. ProcessingInstruction
      37. Range
      38. Text
      39. TimeRanges
      40. TreeWalker
      41. XMLDocument
    0%
    10%
    20%
    30%
    40%
    50%
    60%
    70%
    80%
    90%
    100%