-
Notifications
You must be signed in to change notification settings - Fork 22.4k
/
index.md
72 lines (50 loc) · 1.72 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
---
title: "Document: createEvent() method"
short-title: createEvent()
slug: Web/API/Document/createEvent
page-type: web-api-instance-method
browser-compat: api.Document.createEvent
---
{{APIRef("DOM")}}
> [!WARNING]
> Many methods used with `createEvent`, such as `initCustomEvent`, are deprecated.
> Use [event constructors](/en-US/docs/Web/API/CustomEvent) instead.
Creates an [event](/en-US/docs/Web/API/Event) of the type specified. The
returned object should be first initialized and can then be passed to
{{domxref("EventTarget.dispatchEvent")}}.
## Syntax
```js-nolint
createEvent(type)
```
### Parameters
- `type`
- : A string that represents the type of event to be created. Possible event types include `"UIEvents"`, `"MouseEvents"`, `"MutationEvents"`, and `"HTMLEvents"`. See [Notes](#notes) section for details.
### Return value
An [Event](/en-US/docs/Web/API/Event) object.
## Examples
```js
// Create the event.
const event = document.createEvent("Event");
// Define that the event name is 'build'.
event.initEvent("build", true, true);
// Listen for the event.
elem.addEventListener(
"build",
(e) => {
// e.target matches elem
},
false,
);
// Target can be any Element or other EventTarget.
elem.dispatchEvent(event);
```
## Notes
Event type strings suitable for passing to `createEvent()` are listed in the
[DOM standard — see the table in step 2](https://dom.spec.whatwg.org/#dom-document-createevent). Bear in mind that most event objects now have constructors, which
are the modern recommended way to create event object instances.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Creating and triggering events](/en-US/docs/Web/Events/Creating_and_triggering_events)