| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/EventTarget | [Back] [Original] |
Get to know MDN better
This feature is well established and works across many devices and browser versions. Its been available across browsers since September 2020.
Note: This feature is available in Web Workers.
The EventTarget() constructor creates a new EventTarget object instance.
Note:
It is fairly rare to explicitly call this constructor. Most of the time, this constructor is used inside the constructor of an object extending the EventTarget interface, using the super keyword.
new EventTarget()
None.
A new instance of the EventTarget object.
This example implements a Counter class, with increment() and decrement() methods. It fires a custom "valuechange" event when either of these methods is called.
<button id="dec" aria-label="Decrement">-</button>
<span id="currentValue">0</span>
<button id="inc" aria-label="Increment">+</button>
class Counter extends EventTarget {
constructor(initialValue = 0) {
super();
this.value = initialValue;
}
#emitChangeEvent() {
this.dispatchEvent(new CustomEvent("valuechange", { detail: this.value }));
}
increment() {
this.value++;
this.#emitChangeEvent();
}
decrement() {
this.value--;
this.#emitChangeEvent();
}
}
const initialValue = 0;
const counter = new Counter(initialValue);
document.querySelector("#currentValue").innerText = initialValue;
counter.addEventListener("valuechange", (event) => {
document.querySelector("#currentValue").innerText = event.detail;
});
document.querySelector("#inc").addEventListener("click", () => {
counter.increment();
});
document.querySelector("#dec").addEventListener("click", () => {
counter.decrement();
});
| Specification |
|---|
| DOM # ref-for-dom-eventtarget-eventtarget |
This page was last modified on Jul 26, 2024 by MDN contributors.
EventTargetAbortControllerAbortSignalAbstractRangeAttrCDATASectionCharacterDataCommentCustomEventDOMErrorDOMExceptionDOMImplementationDOMParserDOMTokenListDocumentDocumentFragmentDocumentTypeElementEventHTMLCollectionMutationObserverMutationRecordNamedNodeMapNodeNodeIteratorNodeListProcessingInstructionQuotaExceededErrorRangeShadowRootStaticRangeTextTreeWalkerXMLDocumentXPathEvaluatorXPathExpressionXPathResultXSLTProcessorYour blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |