DOM Events
Event Object
- When an event happens, the browser creates an event object, puts details into it and passes it as an argument to the handler.
event.type
event.target
: the deepest element that originated the event.
event.currentTarget
: the current element that handles the event (the one that has the handler on it)
button1.onclick = function(event) {
console.log(event.type + " at " + event.currentTarget);
console.log("Coordinates: " + event.clientX + ":" + event.clientY);
};
Event Bubbling
- When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
- The process is called “bubbling”, because events “bubble” from the inner element up through parents like a bubble in the water.
<div onclick="alert(event.currentTarget)">
<ul onclick="alert(event.currentTarget)">
<li onclick="alert(event.currentTarget)">text-1</li>
</ul>
</div>
Stop Propagation
- Use
event.stopPropagation
to stop the bubbling,
- Use
event.stopImmediatePropagation()
to stop the bubbling and prevent other handlers on the current element from running.
Event Delegation
- Instead of assigning a handler to each of child element you can put a single handler on their common ancestor.
Prevent browser actions
- Many events automatically lead to certain actions performed by the browser.
- For instance:
- A click on a link – initiates navigation to its URL.
- A click on a form submit button – initiates its submission to the server.
- There are two ways to tell the browser
event.preventDefault()
- If the handler is assigned using
on<event>
(not by addEventListener
), then returning false
also works the same.