forked from whatwg/dom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dom.bs
9169 lines (7275 loc) · 304 KB
/
dom.bs
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<pre class='metadata'>
Title: DOM Standard
H1: DOM
Shortname: dom
Status: LS
Group: WHATWG
No Editor: true
!Participate: <a href=https://github.com/whatwg/dom>GitHub whatwg/dom</a> (<a href=https://github.com/whatwg/dom/issues/new>new issue</a>, <a href=https://github.com/whatwg/dom/issues>open issues</a>, <a href=https://www.w3.org/Bugs/Public/buglist.cgi?component=DOM&product=WebAppsWG&resolution=--->legacy open bugs</a>)
!Participate: <a href=https://wiki.whatwg.org/wiki/IRC>IRC: #whatwg on Freenode</a>
!Commits: <a href=https://github.com/whatwg/dom/commits>GitHub whatwg/dom/commits</a>
!Commits: <a href=https://twitter.com/thedomstandard>@thedomstandard</a>
Logo: https://resources.whatwg.org/logo-dom.svg
Abstract: DOM defines a platform-neutral model for events and node trees.
Ignored Terms: EmptyString, Array, Document
Ignored Vars: p, documentFragment, ev, oldParent, em, processingInstruction, obj, tree, removedNode, C, *, intersects, collapsed
Boilerplate: omit conformance, omit feedback-header
</pre>
<!--
Bikeshed problems:
"Document" isn't properly defining itself, and the force switch isn't working.
-->
<script src=https://resources.whatwg.org/file-issue.js async></script>
<pre class='anchors'>
urlPrefix: https://encoding.spec.whatwg.org/
type: dfn;
text: ascii whitespace
text: utf-8
text: encoding
text: name
text: big5
text: euc-jp
text: euc-kr
text: gbk
text: ibm866
text: iso-2022-jp
text: iso-8859-10
text: iso-8859-13
text: iso-8859-14
text: iso-8859-15
text: iso-8859-16
text: iso-8859-2
text: iso-8859-3
text: iso-8859-4
text: iso-8859-5
text: iso-8859-6
text: iso-8859-7
text: iso-8859-8
text: iso-8859-8-i
text: koi8-r
text: koi8-u
text: shift_jis
text: utf-16be
text: utf-16le
urlPrefix: http://www.w3.org/TR/xml/#NT-
type: type
text: Name; url: Name
text: Char; url: Char
text: PubidChar; url: PubidChar
urlPrefix: http://www.w3.org/TR/xml-names/#NT-
type: type
text: QName; url: QName
urlPrefix: https://heycam.github.io/webidl/
type: dfn; urlPrefix: #dfn-
text: throw
text: dictionary member
text: identifier
text: callback this value
text: supported property indices
text: supported property names
text: unenumerable
text: code unit
type: exception
text: HierarchyRequestError
text: IndexSizeError
text: InUseAttributeError
text: InvalidCharacterError
text: InvalidNodeTypeError
text: InvalidStateError
text: NamespaceError
text: NotFoundError
text: NotSupportedError
text: SyntaxError
text: WrongDocumentError
text: DOMException; urlPrefix: #dfn-
type: interface;
text: DOMTimeStamp; urlPrefix: #common-
urlPrefix: https://html.spec.whatwg.org/multipage/
type: dfn
urlPrefix: webappapis.html
text: report the exception
text: queue a microtask
text: compound microtask
text: execute a compound microtask subtask
urlPrefix: syntax.html
text: html parser
text: html parsing; url: #html-parser
urlPrefix: browsers.html
text: unit of related similar-origin browsing contexts
text: origin
text: effective script origin
text: origin alias; url: #concept-origin-alias
text: Unicode serialization of an origin; url: #unicode-serialisation-of-an-origin
urlPrefix: infrastructure.html
text: in parallel
urlPrefix: https://w3c.github.io/webcomponents/spec/shadow/
type: dfn; urlPrefix: #dfn-
text: shadow root
url: https://w3c.github.io/DOM-Parsing/#widl-Range-createContextualFragment-DocumentFragment-DOMString-fragment
type: method; text: createContextualFragment(); for: Range;
type: interface
urlPrefix: https://w3c.github.io/uievents/#interface-
text: KeyboardEvent
text: MouseEvent
text: UIEvent
url: http://www.w3.org/TR/touch-events/#touchevent-interface
text: TouchEvent
url: https://w3c.github.io/webcomponents/spec/shadow/#the-shadowroot-interface
text: ShadowRoot
</pre>
<pre class='link-defaults'>
spec:html; type:element
text: title
text: script
</pre>
<h2 id=goals class=no-num>Goals</h2>
This specification standardizes the DOM. It does so as follows:
<ol>
<li>
<p>By consolidating <cite>DOM Level 3 Core</cite> [[DOM-Level-3-Core]],
<cite>Element Traversal</cite> [[ELEMENTTRAVERSAL]],
<cite>Selectors API Level 2</cite> [[SELECTORS-API2]], the
"DOM Event Architecture" and "Basic Event Interfaces" chapters of
<cite>DOM Level 3 Events</cite> [[uievents-20031107]] (specific types of events do not
belong in the DOM Standard), and <cite>DOM Level 2 Traversal and Range</cite>
[[DOM-Level-2-Traversal-Range]], and:
<ul class=brief>
<li>Aligning them with the JavaScript ecosystem where possible.
<li>Aligning them with existing implementations.
<li>Simplifying them as much as possible.
</ul>
<li><p>By moving features from the HTML Standard [[!HTML]] that make more sense to be
specified as part of the DOM Standard.
<li>
<p>By defining a replacement for the "Mutation Events" and
"Mutation Name Event Types" chapters of <cite>DOM Level 3 Events</cite>
[[uievents-20031107]] as the old model
was problematic.
<p class="note no-backref">The old model is expected to be removed from implementations
in due course.
<li><p>By defining new features that simplify common DOM operations.
</ol>
<h2 id=conformance>Conformance</h2>
All diagrams, examples, and notes in this specification are
non-normative, as are all sections explicitly marked non-normative.
Everything else in this specification is normative.
The keywords "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
"SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and
"OPTIONAL" in this document are to be interpreted as described in RFC 2119.
For readability, these words do not appear in all uppercase letters in this
specification. [[!RFC2119]]
Requirements phrased in the imperative as part of algorithms
(such as "strip any leading space characters" or "return false and
terminate these steps") are to be interpreted with the meaning of the
keyword ("must", "should", "may", etc.) used in introducing the
algorithm.
Conformance requirements phrased as algorithms or specific steps
may be implemented in any manner, so long as the end result is
equivalent. (In particular, the algorithms defined in this
specification are intended to be easy to follow, and not intended to
be performant.)
<p id="hardwareLimitations">User agents may impose
implementation-specific limits on otherwise unconstrained inputs,
e.g. to prevent denial of service attacks, to guard against running
out of memory, or to work around platform-specific limitations.
When a method or an attribute is said to call another method or attribute, the user agent must invoke its internal API for that attribute or method so that e.g. the author can't change the behavior by overriding attributes or methods with custom properties or functions in JavaScript.
Unless otherwise stated, string comparisons are done in a <a>case-sensitive</a> manner.
<h3 id=dependencies>Dependencies</h3>
The IDL fragments in this specification must be interpreted as
required for conforming IDL fragments, as described in the Web IDL
specification. [[!WEBIDL]]
Some of the terms used in this specification are defined in
<cite>Encoding</cite>, <cite>Selectors</cite>, <cite>Web IDL</cite>, <cite>XML</cite>, and
<cite>Namespaces in XML</cite>.
[[!ENCODING]]
[[!SELECTORS4]]
[[!WEBIDL]]
[[!XML]]
[[!XML-NAMES]]
<h3 id=extensibility>Extensibility</h3>
Vendor-specific proprietary extensions to this specification are
strongly discouraged. Authors must not use such extensions, as
doing so reduces interoperability and fragments the user base,
allowing only users of specific user agents to access the content in
question.
When extensions are needed, the DOM Standard can be updated accordingly, or a new standard
can be written that hooks into the provided extensibility hooks for
<dfn export lt="other applicable specifications">applicable specifications</dfn>.
<!-- https://www.w3.org/mid/[email protected] -->
<h2 id=terminology>Terminology</h2>
The term <dfn export>context object</dfn> means the object on which the algorithm,
attribute getter, attribute setter, or method being discussed was called. When the
<a>context object</a> is unambiguous, the term can be omitted.
<!-- XXX we should prolly explain that "set attribute X to Y" works even for
readonly attributes when it is language for implementors -->
<h3 id=trees>Trees</h3> <!-- Sorry reddit, this is not /r/trees -->
A <dfn export id=concept-tree>tree</dfn> is a finite hierarchical tree structure. In
<dfn export id=concept-tree-order>tree order</dfn> is preorder, depth-first
traversal of a <a>tree</a>.
<!-- http://en.wikipedia.org/wiki/Tree_traversal#Depth-first_Traversal -->
An object that <dfn export for=tree id=concept-tree-participate lt="participate">participates</dfn> in
a <a>tree</a> has a
<dfn export for=tree id=concept-tree-parent>parent</dfn>, which is either another object
or null, and an ordered list of zero or more
<dfn export for=tree id=concept-tree-child lt="child|children">child</dfn> objects. An object <var>A</var> whose
<a>parent</a> is object <var>B</var> is a
<a>child</a> of <var>B</var>.
The <dfn export for=tree id=concept-tree-root>root</dfn> of an object is itself, if its
<a>parent</a> is null, or else it is the
<a for=tree>root</a> of its
<a>parent</a>.
An object <var>A</var> is called a
<dfn export for=tree id=concept-tree-descendant>descendant</dfn> of an object
<var>B</var>, if either <var>A</var> is a
<a>child</a> of <var>B</var> or
<var>A</var> is a <a>child</a> of an
object <var>C</var> that is a
<a>descendant</a> of <var>B</var>.
An
<dfn export for=tree id=concept-tree-inclusive-descendant>inclusive descendant</dfn> is
an object or one of its
<a>descendants</a>.
An object <var>A</var> is called an
<dfn export for=tree id=concept-tree-ancestor>ancestor</dfn> of an object
<var>B</var> if and only if <var>B</var> is a
<a>descendant</a> of
<var>A</var>.
An <dfn export for=tree id=concept-tree-inclusive-ancestor>inclusive ancestor</dfn> is
an object or one of its <a>ancestors</a>.
An object <var>A</var> is called a
<dfn export for=tree id=concept-tree-sibling>sibling</dfn> of an object
<var>B</var>, if and only if <var>B</var> and <var>A</var>
share the same non-null <a>parent</a>.
An <dfn export for=tree id=concept-tree-inclusive-sibling>inclusive sibling</dfn> is an
object or one of its <a>siblings</a>.
An object <var>A</var> is
<dfn export for=tree id=concept-tree-preceding>preceding</dfn> an object
<var>B</var> if <var>A</var> and <var>B</var> are in the
same <a>tree</a> and <var>A</var> comes
before <var>B</var> in
<a>tree order</a>.
An object <var>A</var> is
<dfn export for=tree id=concept-tree-following>following</dfn> an object
<var>B</var> if <var>A</var> and <var>B</var> are in the
same <a>tree</a> and <var>A</var> comes
after <var>B</var> in
<a>tree order</a>.
The <dfn export for=tree id=concept-tree-first-child>first child</dfn> of an object is its
first <a>child</a> or null if it has no <a>children</a>.
The <dfn export for=tree id=concept-tree-last-child>last child</dfn> of an object is its
last <a>child</a> or null if it has no <a>children</a>.
The <dfn export for=tree id=concept-tree-previous-sibling>previous sibling</dfn> of an
object is its first <a>preceding</a>
<a>sibling</a> or null if it has no
<a>preceding</a>
<a>sibling</a>.
The <dfn export for=tree id=concept-tree-next-sibling>next sibling</dfn> of an
object is its first <a>following</a>
<a>sibling</a> or null if it has no
<a>following</a>
<a>sibling</a>.
The <dfn export for=tree id=concept-tree-index>index</dfn> of an object is its number
of <a>preceding</a>
<a>siblings</a>.
<h3 id=strings>Strings</h3>
Comparing two strings in a
<dfn export lt="case-sensitive|case-sensitively">case-sensitive</dfn> manner means
comparing them exactly, code point for code point.
Comparing two strings in a
<dfn export lt="ASCII case-insensitive|ASCII case-insensitively">ASCII case-insensitive</dfn>
manner means comparing them exactly, code point for code point, except that the characters
in the range U+0041 to U+005A (i.e. LATIN CAPITAL LETTER A to LATIN CAPITAL LETTER Z),
inclusive, and the corresponding characters in the range U+0061 to U+007A (i.e.
LATIN SMALL LETTER A to LATIN SMALL LETTER Z), inclusive, are considered to also match.
<dfn export lt="converted to ASCII uppercase">Converting a string to ASCII uppercase</dfn>
means replacing all characters in the range U+0061 to U+007A, inclusive, with the
corresponding characters in the range U+0041 to U+005A, inclusive.
<dfn export lt="converted to ASCII lowercase">Converting a string to ASCII lowercase</dfn>
means replacing all characters in the range U+0041 to U+005A, inclusive, with the
corresponding characters in the range U+0061 to U+007A, inclusive.
A string <var>pattern</var> is a <dfn export>prefix match</dfn> for a string <var>s</var>
when <var>pattern</var> is not longer than <var>s</var> and truncating <var>s</var> to
<var>pattern</var>'s length leaves the two strings as matches of each other.
<h3 id="ordered sets">Ordered sets</h3>
The <dfn export id=concept-ordered-set-parser>ordered set parser</dfn> takes a string
<var>input</var> and then runs these steps:
<ol>
<li>Let <var>position</var> be a pointer into <var>input</var>,
initially pointing at the start of the string.
<li>Let <var>tokens</var> be an ordered set of tokens, initially empty.
<li><a>Skip ASCII whitespace</a>.
<li>While <var>position</var> is not past the end of
<var>input</var>:
<ol>
<li><a>Collect a code point sequence</a> of code points that are
not <a>ASCII whitespace</a>.
<li>If the collected string is not in <var>tokens</var>, append the
collected string to <var>tokens</var>.
<li><a>Skip ASCII whitespace</a>.
</ol>
<li>Return <var>tokens</var>.
</ol>
To <dfn export>collect a code point sequence</dfn> of
<var>code points</var>, run these steps:
<ol>
<li>Let <var>input</var> and <var>position</var> be the same
variables as those of the same name in the algorithm that invoked these
steps.
<li>Let <var>result</var> be the empty string.
<li>While <var>position</var> does not point past the end of
<var>input</var> and the code point at <var>position</var> is
one of <var>code points</var>, append that code point to the end
of <var>result</var> and advance <var>position</var> to the
next code point in <var>input</var>.
<li>Return <var>result</var>.
</ol>
To <dfn export>skip ASCII whitespace</dfn> means to
<a>collect a code point sequence</a> of
<a>ASCII whitespace</a> and discard the
return value.
The <dfn export id=concept-ordered-set-serializer>ordered set serializer</dfn> takes a
<var>set</var> and returns the concatenation of the strings in <var>set</var>, separated from each other by U+0020, if <var>set</var> is non-empty, and the empty string otherwise.
<h3 id=selectors>Selectors</h3>
To <dfn export>match a relative selectors string</dfn> <var>relativeSelectors</var>
against a <var>set</var>, run these steps:
<ol>
<li>Let <var>s</var> be the result of
<a>parse a relative selector</a> from
<var>relativeSelectors</var> against <var>set</var>.
[[!SELECTORS4]]
<li>If <var>s</var> is failure, <a>throw</a> a {{SyntaxError}}.
<li>Return the result of <a>evaluate a selector</a> <var>s</var>
using <a>:scope elements</a> <var>set</var>. [[!SELECTORS4]]
</ol>
To <dfn export>scope-match a selectors string</dfn> <var>selectors</var> against a
<var>node</var>, run these steps:
<ol>
<li>Let <var>s</var> be the result of
<a>parse a selector</a> <var>selectors</var>.
[[!SELECTORS4]]
<li>If <var>s</var> is failure, <a>throw</a> a
{{SyntaxError}}.
<li>Return the result of <a>evaluate a selector</a>
<var>s</var> against
<var>node</var>'s <a for=tree>root</a> using
<a>scoping root</a> <var>node</var> and
scoping method
<a>scope-filtered</a>.
[[!SELECTORS4]].
</ol>
<p class=note>Support for namespaces within selectors is not planned and will not be
added.
<h3 id=namespaces>Namespaces</h3>
The <dfn export>HTML namespace</dfn> is
<code>http://www.w3.org/1999/xhtml</code>.
The <dfn export>XML namespace</dfn> is
<code>http://www.w3.org/XML/1998/namespace</code>.
The <dfn export>XMLNS namespace</dfn> is
<code>http://www.w3.org/2000/xmlns/</code>.
To <dfn export>validate</dfn> a <var>qualifiedName</var>, run these steps:
<ol>
<li>If <var>qualifiedName</var> does not match the
<code><a type>Name</a></code> production, <a>throw</a>
an {{InvalidCharacterError}} exception.
<li>If <var>qualifiedName</var> does not match the
<code><a type>QName</a></code> production,
<a>throw</a> a {{NamespaceError}} exception.
</ol>
To <dfn export>validate and extract</dfn> a <var>namespace</var> and <var>qualifiedName</var>,
run these steps:
<ol>
<li>If <var>namespace</var> is the empty string, set it to null.
<li><a>Validate</a> <var>qualifiedName</var>. Rethrow any exceptions.
<li>Let <var>prefix</var> be null.
<li>Let <var>localName</var> be <var>qualifiedName</var>.
<li>If <var>qualifiedName</var> contains a "<code>:</code>" (U+003E), then split the
string on it and set <var>prefix</var> to the part before and <var>localName</var> to
the part after.
<li>If <var>prefix</var> is non-null and <var>namespace</var> is null,
<a>throw</a> a {{NamespaceError}} exception.
<li>If <var>prefix</var> is "<code>xml</code>" and <var>namespace</var> is
not the <a>XML namespace</a>, <a>throw</a> a
{{NamespaceError}} exception.
<li>If either <var>qualifiedName</var> or <var>prefix</var> is
"<code>xmlns</code>" and <var>namespace</var> is not the
<a>XMLNS namespace</a>, <a>throw</a> a
{{NamespaceError}} exception.
<li>If <var>namespace</var> is the <a>XMLNS namespace</a> and neither
<var>qualifiedName</var> nor <var>prefix</var> is "<code>xmlns</code>",
<a>throw</a> a {{NamespaceError}} exception.
<li>Return <var>namespace</var>, <var>prefix</var>, and <var>localName</var>.
</ol>
<h2 id=events>Events</h2>
<h3 id=introduction-to-dom-events>Introduction to "DOM Events"</h3>
Throughout the web platform <a>events</a> are <a>dispatched</a> to objects to signal an
occurrence, such as network activity or user interaction. These objects implement the
{{EventTarget}} interface and can therefore add <a>event listeners</a> to observe
<a>events</a> by calling {{EventTarget/addEventListener()}}:
<pre class=lang-javascript>
obj.addEventListener("load", imgFetched)
function imgFetched(ev) {
// great success
…
}
</pre>
<a>Event listeners</a> can be removed
by utilizing the
{{EventTarget/removeEventListener()}}
method, passing the same arguments.
<a>Events</a> are objects too and implement the
{{Event}} interface (or a derived interface). In the example above
<var>ev</var> is the <a>event</a>. It is
passed as argument to
<a>event listener</a>'s <b>callback</b>
(typically a JavaScript Function as shown above).
<a>Event listeners</a> key off the
<a>event</a>'s
{{Event/type}} attribute value
("<code>load</code>" in the above example). The
<a>event</a>'s
{{Event/target}} attribute value returns the
object to which the <a>event</a> was
<a>dispatched</a>
(<var>obj</var> above).
Now while typically <a>events</a> are
<a>dispatched</a> by the user agent as
the result of user interaction or the completion of some task, applications
can <a>dispatch</a>
<a>events</a> themselves, commonly known as
synthetic events:
<pre class='lang-javascript'>
// add an appropriate event listener
obj.addEventListener("cat", function(e) { process(e.detail) })
// create and dispatch the event
var event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}})
obj.dispatchEvent(event)
</pre>
Apart from signaling, <a>events</a> are
sometimes also used to let an application control what happens next in an
operation. For instance as part of form submission an
<a>event</a> whose
{{Event/type}} attribute value is
"<code>submit</code>" is
<a>dispatched</a>. If this
<a>event</a>'s
{{Event/preventDefault()}} method is
invoked, form submission will be terminated. Applications who wish to make
use of this functionality through <a>events</a>
<a>dispatched</a> by the application
(synthetic events) can make use of the return value of the
{{EventTarget/dispatchEvent()}} method:
<pre class='lang-javascript'>
if(obj.dispatchEvent(event)) {
// event was not canceled, time for some magic
…
}
</pre>
When an <a>event</a> is
<a>dispatched</a> to an object that
<a>participates</a> in a
<a>tree</a> (e.g. an
<a for="/">element</a>), it can reach
<a>event listeners</a> on that object's
<a>ancestors</a> too. First all object's
<a>ancestor</a>
<a>event listeners</a> whose
<b>capture</b> variable is set to true are invoked, in
<a>tree order</a>. Second, object's own
<a>event listeners</a> are invoked. And
finally, and only if <a>event</a>'s
{{Event/bubbles}} attribute value is true,
object's <a>ancestor</a>
<a>event listeners</a> are invoked again,
but now in reverse <a>tree order</a>.
Lets look at an example of how <a>events</a> work in a <a>tree</a>:
<pre class='lang-markup'>
<!doctype html>
<html>
<head>
<title>Boring example</title>
</head>
<body>
<p>Hello <span id=x>world</span>!</p>
<script>
function test(e) {
debug(e.target, e.currentTarget, e.eventPhase)
}
document.addEventListener("hey", test, {capture: true})
document.body.addEventListener("hey", test)
var ev = new Event("hey", {bubbles:true})
document.getElementById("x").dispatchEvent(ev)
</script>
</body>
</html>
</pre>
The <code>debug</code> function will be invoked twice. Each time the <a>event</a>'s
{{Event/target}} attribute value will be the
<code>span</code> <a for="/">element</a>. The
first time {{Event/currentTarget}} attribute's
value will be the <a>document</a>, the second
time the <code>body</code> <a for="/">element</a>.
{{Event/eventPhase}} attribute's value
switches from {{Event/CAPTURING_PHASE}}
to {{Event/BUBBLING_PHASE}}. If an
<a>event listener</a> was registered for
the <code>span</code> <a for="/">element</a>,
{{Event/eventPhase}} attribute's value
would have been {{Event/AT_TARGET}}.
<h3 id=interface-event>Interface {{Event}}</h3>
<pre class="idl">
[Constructor(DOMString type, optional EventInit eventInitDict),
Exposed=(Window,Worker)]
interface Event {
readonly attribute DOMString type;
readonly attribute EventTarget? target;
readonly attribute EventTarget? currentTarget;
const unsigned short NONE = 0;
const unsigned short CAPTURING_PHASE = 1;
const unsigned short AT_TARGET = 2;
const unsigned short BUBBLING_PHASE = 3;
readonly attribute unsigned short eventPhase;
void stopPropagation();
void stopImmediatePropagation();
readonly attribute boolean bubbles;
readonly attribute boolean cancelable;
void preventDefault();
readonly attribute boolean defaultPrevented;
[Unforgeable] readonly attribute boolean isTrusted;
readonly attribute DOMTimeStamp timeStamp;
void initEvent(DOMString type, boolean bubbles, boolean cancelable);
};
dictionary EventInit {
boolean bubbles = false;
boolean cancelable = false;
};
</pre>
An <dfn export id=concept-event>event</dfn> allows for signaling that
something has occurred, e.g. that an image has completed downloading. It is
represented by the {{Event}} interface or an interface that
inherits from the {{Event}} interface.
<dl class=domintro>
<dt><code><var>event</var> = new <a constructor lt="Event()">Event</a>(<var>type</var> [, <var>eventInitDict</var>])</code>
<dd>Returns a new <var>event</var> whose
{{Event/type}} attribute value is set to
<var>type</var>. The optional {{Event/Event()/eventInitDict!!argument}} argument
allows for setting the {{Event/bubbles}} and
{{Event/cancelable}} attributes via object
members of the same name.
<dt><code><var>event</var> . {{Event/type}}</code>
<dd>Returns the type of <var>event</var>, e.g.
"<code>click</code>", "<code>hashchange</code>", or
"<code>submit</code>".
<dt><code><var>event</var> . {{Event/target}}</code>
<dd>Returns the object to which <var>event</var> is <a>dispatched</a>.
<dt><code><var>event</var> . {{Event/currentTarget}}</code>
<dd>Returns the object whose <a>event listener</a>'s <b>callback</b> is currently being
invoked.
<dt><code><var>event</var> . {{Event/eventPhase}}</code>
<dd>Returns the <a>event</a>'s phase, which is one of {{Event/NONE}},
{{Event/CAPTURING_PHASE}},
{{Event/AT_TARGET}}, and
{{Event/BUBBLING_PHASE}}.
<dt><code><var>event</var> . <a method for=Event lt="stopPropagation()">stopPropagation</a>()</code>
<dd>When <a>dispatched</a> in a <a>tree</a>, invoking this method prevents
<var>event</var> from reaching any objects other than the current object.
<dt><code><var>event</var> . <a method for=Event lt="stopImmediatePropagation()">stopImmediatePropagation</a>()</code>
<dd>Invoking this method prevents <var>event</var> from reaching
any registered <a>event listeners</a> after the current one finishes running and, when
<a>dispatched</a> in a <a>tree</a>, also prevents <var>event</var> from reaching any
other objects.
<dt><code><var>event</var> . {{Event/bubbles}}</code>
<dd>Returns true or false depending on how <var>event</var> was initialized. True if
<var>event</var> goes through its {{Event/target}} attribute value's <a>ancestors</a>
in reverse <a>tree order</a>, and false otherwise.
<dt><code><var>event</var> . {{Event/cancelable}}</code>
<dd>Returns true or false depending on how <var>event</var> was initialized. Its return
value does not always carry meaning, but true can indicate that part of the operation
during which <var>event</var> was <a>dispatched</a>, can be canceled by invoking the
{{Event/preventDefault()}} method.
<dt><code><var>event</var> . <a method for=Event lt="preventDefault()">preventDefault</a>()</code>
<dd>If invoked when the {{Event/cancelable}} attribute value is true, and while executing a
listener for the <var>event</var> with {{EventListenerOptions/passive}} set to false, signals to
the operation that caused <var>event</var> to be <a>dispatched</a> that it needs to be canceled.
<dt><code><var>event</var> . {{Event/defaultPrevented}}</code>
<dd>Returns true if {{Event/preventDefault()}} was invoked successfully to indicate cancellation,
and false otherwise.
<dt><code><var>event</var> . {{Event/isTrusted}}</code>
<dd>Returns true if <var>event</var> was
<a>dispatched</a> by the user agent, and
false otherwise.
<dt><code><var>event</var> . {{Event/timeStamp}}</code>
<dd>Returns the creation time of <var>event</var> as the number of milliseconds that
passed since 00:00:00 UTC on 1 January 1970.
<!-- initEvent is dead -->
</dl>
The <dfn attribute for=Event>type</dfn> attribute must
return the value it was initialized to. When an
<a>event</a> is created the attribute must be
initialized to the empty string.
The <dfn attribute for=Event>target</dfn> and
<dfn attribute for=Event>currentTarget</dfn>
attributes must return the values they were initialized to. When an
<a>event</a> is created the attributes must be
initialized to null.
The <dfn attribute for=Event>eventPhase</dfn>
attribute must return the value it was initialized to, which must be one of
the following:
<dl>
<dt><dfn const for=Event>NONE</dfn> (numeric value 0)
<dd><a>Events</a> not currently
<a>dispatched</a> are in this phase.
<dt><dfn const for=Event>CAPTURING_PHASE</dfn> (numeric value 1)
<dd>When an <a>event</a> is
<a>dispatched</a> to an object that
<a>participates</a> in a
<a>tree</a> it will be in this phase before it
reaches its {{Event/target}} attribute value.
<dt><dfn const for=Event>AT_TARGET</dfn> (numeric value 2)
<dd>When an <a>event</a> is
<a>dispatched</a> it will be in this
phase on its {{Event/target}} attribute value.
<dt><dfn const for=Event>BUBBLING_PHASE</dfn> (numeric value 3)
<dd>When an <a>event</a> is
<a>dispatched</a> to an object that
<a>participates</a> in a
<a>tree</a> it will be in this phase after it
reaches its {{Event/target}} attribute value.
</dl>
Initially the attribute must be initialized to
{{Event/NONE}}.
<hr>
Each <a>event</a> has the following associated
flags that are all initially unset:
<ul>
<li><dfn export for=Event id=stop-propagation-flag>stop propagation flag</dfn>
<li><dfn export for=Event id=stop-immediate-propagation-flag>stop immediate propagation flag</dfn>
<li><dfn export for=Event id=canceled-flag>canceled flag</dfn>
<li><dfn export for=Event id=initialized-flag>initialized flag</dfn>
<li><dfn export for=Event id=dispatch-flag>dispatch flag</dfn>
<li><dfn export for=Event id=in-passive-listener-flag>in passive listener flag</dfn>
</ul>
The
<dfn method for=Event>stopPropagation()</dfn>
method must set the <a>stop propagation flag</a>.
The
<dfn method for=Event>stopImmediatePropagation()</dfn>
method must set both the <a>stop propagation flag</a> and
<a>stop immediate propagation flag</a>.
The <dfn attribute for=Event>bubbles</dfn> and
<dfn attribute for=Event>cancelable</dfn> attributes
must return the values they were initialized to.
The <dfn method for=Event><code>preventDefault()</code></dfn> method, when invoked, must set the
<a>canceled flag</a> if the {{Event/cancelable}} attribute value is true and the
<a>in passive listener flag</a> is unset.
<p class="note no-backref">This means there are scenarios where invoking {{preventDefault()}} has no
effect. User agents are encouraged to log the precise cause in a developer console, to aid
debugging.
The
<dfn attribute for=Event>defaultPrevented</dfn>
attribute must return true if the <a>canceled flag</a> is set and
false otherwise.
<hr>
The <dfn attribute for=Event>isTrusted</dfn> attribute
must return the value it was initialized to. When an
<a>event</a> is created the attribute must be
initialized to false.
The <dfn attribute for=Event>timeStamp</dfn> attribute
must return the value it was initialized to. When an
<a>event</a> is created the attribute must be
initialized to the number of milliseconds that have passed since
00:00:00 UTC on 1 January 1970, ignoring leap seconds.
<!-- leap seconds are ignored by JavaScript too -->
<hr>
To <dfn export for=Event id=concept-event-initialize>initialize</dfn> an
<var>event</var>, with <var>type</var>,
<var>bubbles</var>, and <var>cancelable</var>, run these steps:
<ol>
<li>Set the <a>initialized flag</a>.
<li>Unset the <a>stop propagation flag</a>,
<a>stop immediate propagation flag</a>, and
<a>canceled flag</a>.
<li>Set the {{Event/isTrusted}} attribute
to false.
<li>Set the {{Event/target}} attribute to
null.
<li>Set the {{Event/type}} attribute to
<var>type</var>.
<li>Set the {{Event/bubbles}} attribute to
<var>bubbles</var>.
<li>Set the {{Event/cancelable}} attribute
to <var>cancelable</var>.
</ol>
The
<dfn method for=Event>initEvent(<var>type</var>, <var>bubbles</var>, <var>cancelable</var>)</dfn>
method, when invoked, must run these steps:
<ol>
<li>If <a>context object</a>'s <a>dispatch flag</a> is set, terminate
these steps.
<li><a>Initialize</a> the
<a>context object</a> with <var>type</var>, <var>bubbles</var>, and
<var>cancelable</var>.
</ol>
<p class="note no-backref">As <a>events</a> have constructors
{{Event/initEvent()}} is superfluous. However,
it has to be supported for legacy content.
<h3 id=interface-customevent>Interface {{CustomEvent}}</h3>
<pre class=idl>
[Constructor(DOMString type, optional CustomEventInit eventInitDict),
Exposed=(Window,Worker)]
interface CustomEvent : Event {
readonly attribute any detail;
void initCustomEvent(DOMString type, boolean bubbles, boolean cancelable, any detail);
};
dictionary CustomEventInit : EventInit {
any detail = null;
};
</pre>
<a>Events</a> using the
{{CustomEvent}} interface can be used to carry custom data.
<dl class=domintro>
<dt><code><var>event</var> = new <a constructor lt="CustomEvent()">CustomEvent</a>(<var>type</var> [, <var>eventInitDict</var>])</code>
<dd>Works analogously to the constructor for {{Event}} except
that the optional <var>eventInitDict</var> argument now
allows for setting the {{CustomEvent/detail}} attribute
too.
<dt><code><var>event</var> . {{CustomEvent/detail}}</code>
<dd>Returns any custom data <var>event</var> was created with.
Typically used for synthetic events.
<!-- initCustomEvent is dead -->
</dl>
The <dfn attribute for=CustomEvent>detail</dfn> attribute
must return the value it was initialized to.
The
<dfn method for=CustomEvent>initCustomEvent(<var>type</var>, <var>bubbles</var>, <var>cancelable</var>, <var>detail</var>)</dfn>
method must, when invoked, run these steps:
<ol>
<li>If <a>context object</a>'s <a>dispatch flag</a> is set, terminate
these steps.
<li><a>Initialize</a> the
<a>context object</a> with <var>type</var>, <var>bubbles</var>, and
<var>cancelable</var>.
<li>Set <a>context object</a>'s {{CustomEvent/detail}}
attribute to <var>detail</var>.
</ol>
<h3 id=constructing-events>Constructing events</h3>
When a <dfn export for=Event id=concept-event-constructor>constructor</dfn> of the
{{Event}} interface, or of an interface that inherits from the {{Event}} interface, is
invoked, these steps must be run:
<ol>
<li><p>Create an <a>event</a> that uses the interface the constructor was invoked upon.
<li><p>Set its <a>initialized flag</a>.
<li><p>Initialize the {{Event/type}} attribute to the <var>type</var> argument.
<li><p>If there is an <var>eventInitDict</var> argument, then for each
<a>dictionary member</a> present, find the attribute on <a>event</a> whose
<a>identifier</a> matches the key of the <a>dictionary member</a> and then set the
attribute to the value of that <a>dictionary member</a>.
<li><p>Return the <a>event</a>.
</ol>
<h3 id=defining-event-interfaces>Defining event interfaces</h3>
In general, when defining a new interface that inherits from {{Event}} please always ask
feedback from the <a href=https://whatwg.org/>WHATWG</a> or the
<a href=http://www.w3.org/2008/webapps/>W3C WebApps WG</a> community.
The {{CustomEvent}} interface can be used as starting point.
However, do not introduce any <code>init<var>*</var>Event()</code>
methods as they are redundant with constructors. Interfaces that inherit
from the {{Event}} interface that have such a method only have it
for historical reasons.
<h3 id=interface-eventtarget>Interface {{EventTarget}}</h3>
<pre class=idl>
[Exposed=(Window,Worker)]
interface EventTarget {
void addEventListener(DOMString type, EventListener? callback, optional (EventListenerOptions or boolean) options);
void removeEventListener(DOMString type, EventListener? callback, optional (EventListenerOptions or boolean) options);
boolean dispatchEvent(Event event);
};
callback interface EventListener {
void handleEvent(Event event);
};
dictionary EventListenerOptions {
boolean capture;
boolean passive;
};
</pre>
{{EventTarget}} is an object to which an
<a>event</a> is
<a>dispatched</a> when something has
occurred. Each {{EventTarget}} has an associated list of
<a>event listeners</a>.
<p>An <dfn export id=concept-event-listener>event listener</dfn> can be used to observe a specific
<a>event</a>.