DOM

DOM

Source

Although events are typically dispatched by the user agent
as the result of user interaction or the completion of some task, applications can dispatch events themselves by using what are commonly known as synthetic events:


// 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)

Apart from signaling, events are
sometimes also used to let an application control what happens next in an
operation. For instance as part of form submission an event whose type attribute value is
"submit" is dispatched. If this event’s preventDefault() method is
invoked, form submission will be terminated. Applications who wish to make
use of this functionality through events dispatched by the application
(synthetic events) can make use of the return value of the dispatchEvent() method:


if(obj.dispatchEvent(event)) { // event was not canceled, time for some magic …
}

When an event is dispatched to an object that participates in a tree (e.g., an element), it can reach event listeners on that object’s ancestors too. Effectively, all the object’s inclusive ancestor event listeners whose capture is true are invoked, in tree order. And then, if event’s bubbles is true, all the object’s inclusive ancestor event listeners whose capture is false are invoked, now in
reverse tree order.

Let’s look at an example of how events work in a tree:


<!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>

The debug function will be invoked twice. Each time the event’s target attribute value will be the span element. The first time currentTarget attribute’s value will be the document, the second time the body element. eventPhase attribute’s value switches from CAPTURING_PHASE to BUBBLING_PHASE. If an event listener was registered
for the span element, eventPhase attribute’s value would have
been AT_TARGET.

Event

In all current engines.

Firefox1+Safari1+Chrome1+ Opera4+Edge79+ Edge (Legacy)12+IE6+ Firefox for Android4+iOS Safari1+Chrome for Android18+Android WebView1+Samsung Internet1.0+Opera Mobile10.1+ Node.js14.5.0+

Event/Event

In all current engines.

Firefox11+Safari6+Chrome15+ Opera11.6+Edge79+ Edge (Legacy)12+IENone Firefox for Android14+iOS Safari6+Chrome for Android18+Android WebView37+Samsung Internet1.0+Opera Mobile12+ Node.js15.0.0+



Read Next page

Report Page