Event handlers can be assigned directly using the equal (=) operator because they are attributes of HTML/DOM elements as well. The syntax is as follows:
For registering handlers, there are two recommended methods. By assigning the event handler code to the target element's corresponding on event property or by adding the handler as a listener for the element using the addEventListener() method, the event handler code can be made to execute when an event is triggered. The handler will receive an object that complies with the Event interface in either scenario (or a derived interface). The main difference is that using the event listener methods, additional event handlers can be added (or removed).
- Capturing Phase: In the capture phase, generally known as the trickling phase, the event "trickles down" to the element that caused the event.
- Target Phase: It starts with the element and handler at the top level and works its way down to the element. When the event arrives at the target, the capture phase is over.
- Bubbling Phase: The event is "bubbled" up to the DOM tree during the bubble phase. The innermost handler initially captures and handles it (the one that is closest to the element on which the event occurred). After that, it moves up (or bubbles up) to the DOM tree's higher levels, moves up to its parents, and eventually returns to its root.
They follow the same order as listed above. As shown in the diagram below:
In event handling, when an event reaches the element, it enters the capturing phase. Events enter the target phase when they reach the element, and they up from the element during the bubbling phase.
HTML Event Handler Attributes
The names of event handlers typically start with on; for example, onclick is the name of the event handler for the click event. Use an HTML attribute with the name of the event handler to assign an event handler to an event connected to an HTML element. For example, you may use the following to run some code when a button is clicked:
In this example, the alert box appears when the button is clicked.
A function defined in a script can be called by an event handler defined in HTML. For example:
When using event handlers as attributes of an HTML element, the following are some important aspects:
First, without explicitly defining the event, the event object can be accessed by the code in the event handler:
Second, the event's target element is represented by the this value inside the event handler:
Third, the element's properties can be accessed by the event handler, as shown below:
Due to the following reasons, assigning event handlers using HTML event handler attributes is not regarded as a good practice and should be avoided as much as possible in event handling:
- The event handler code is first mixed in with the HTML code, making it more difficult to extend and maintain.
Event handler functions accept an argument, the event object, even though we haven't used it up to this point. Additional information about the event is also included in this object. For example, we can check the event object's button property to verify which mouse button was pressed.
For the majority of event types, the handlers registered on nodes with the children will get children-level events. If the button within a paragraph is clicked, the paragraph's event handlers can also see that click event. If both the button and the paragraph have a handler, the handler on the button, which is more specific, will execute first.
The event is said to propagate outward, from the node where it occurred to the parent node of that node and then to the document's root. After every handlers registered on the particular node has had their chance to respond to the event, the handlers that registered on the entire window are given the chance to do so.
This allows you to implement custom keyboard shortcuts and context menus. It may also be used to interfere obnoxiously with the expected behavior of users. For example, the following link cannot be followed:
|Onkeydown||This event is triggered when the user is pressing a key.|
|Onkeypress||This event is triggered when the user presses the key.|
|Onkeyup||This event is triggered when the user releases the key.|
Despite its name, "keydown" is not only triggered when a key is physically pushed. When a key is pushed and held, the event is triggered each time the key is repeated. Or sometimes, you must take extra care in this case. For instance, If we add a button to the Document Object Model when a key is pushed and delete it when the key is released. Now, if the key is held down longer you may accidentally add hundreds of buttons.
Pointer events are the DOM (Document Object Model) events that are triggered for a pointing device. There are some common methods for pointing at objects on a screen such as mouse (including devices that act like mice, such as trackballs and touchpads), stylus/pen, and touchscreens. The pointer is a device that is hardware-independent and can target a specific set of screen coordinates.
When any mouse button is pressed, a number of events are triggered. Similar to the "keydown" and "keyup", the "mouseup" and "mousedown" events are also fired when the mouse button is pushed and released. And, these occur on the DOM nodes directly under the mouse pointer at the time the event happens.
After the event, "mouseup", the "click" event is fired on the most specified node which contains both the button press and release. For example, if we hold down the mouse button on one paragraph, and move the pointer to another paragraph, then release the button, the event "click" will occur on the element containing both paragraphs.
Events and the Event Loop
Event handlers function similarly to other asynchronous notifications. They are scheduled to run when the event occurs but must wait for other scripts to complete before they can execute.
The call stack is responsible for keeping track of all operations in the execution queue. A function is popped from the stack whenever it completes.
The event queue is responsible for sending new functions for processing to the stack. It complies with the queue data structure in order to maintain the correct execution order of all operations.
The event loop facilitates this process by continuously checking whether the call stack is empty. If it is empty, the event queue is used to add new functions. If not, the current function call is then executed.
Sometimes it is necessary to cancel a previously scheduled event. This is actually done by storing the value returned by setTimeout and then calling clearTimeout on the value.
Debouncing is a programming method for preventing time-consuming tasks from firing so frequently that they slow down the performance of a web page. In other words, it limits the frequency of function calls.
No matter how many times you click the debounce button, it gets executed once every 3 seconds!!
DOM Level 0 Event Handlers
In this example, the function here becomes the method of the element button. And, the this value is therefore similar to the element. therefore within the event handler, we can access the property of the element:
In the event handler, you can access the properties of the element and methods by using the this value. And set the event handler property's value to null to remove the event handler as shown below:
The DOM Level 0 event handlers are still widely used due to their simplicity and browser compatibility.
DOM Level 2 Event Handlers
DOM Level 2 Event Handlers provides two primary methods for registering and deregistering event listeners:
- removeEventListener() – It is an inbuilt function that removes an event handler from an element for an attached event.
The addEventListener() Method
This method takes three arguments: an event handler function, an event name, and a Boolean value instructing the method to invoke the event handler during the bubble phase (false) or the capture phase (true). As shown below:
Multiple event handlers can be added to handle a single event, as shown below:
The removeEventListener() Method
The removeEventListener() function removes an event listener added with the addEventListener() function (). However, you must pass the same arguments passed to addEventListener(). For example:
Using an anonymous event listener will not work for the following:
Which is Better - an Inline Event or addEventListener?
Before considering which one is better let's understand the differences first.
- addEventListener allows you to register an unlimited number of event handlers.
- removeEventListener can be used to delete the event handlers.
- Inline events can be overwritten.
- The useCapture flag indicates whether an event should be processed during the bundle phase or the capture phase.
- Events are handled similarly in a browser. When the browser notices a change, it notifies an event handler (a function) that is listening to a specific event. The actions are then carried out as defined by these functions.
- When an event, such as clicking an element or pressing a keyboard key, occurs on an HTML or DOM element, we can invoke specific functions based on these events.
- Event handlers can be assigned directly using the equal (=) operator because they are attributes of HTML/DOM elements as well.
- When an event reaches the element, it enters the capturing phase. Events enter the target phase when they reach the element, they up from the element during the bubbling phase.
- Event handler functions accept an argument, the event object, even though we haven't used it up to this point. Additional information about the event is also included in this object.