This article is a summary(with examples) of the events page on MDN web docs if you want to study in-depth you can refer here
Table of Contents
Events are actions that happen in a system. The system fires a signal when an event occurs and provides a mechanism to perform a task or activity automatically.
Example of event
hovering over an element, clicking, scrolling, etc.
Each event has an event handler that executes a block of code when an event is fired.
There are two types of events, Browser events, and Synthetic events.
Browser events are built-in, predetermined, and are executed by the browser when an action occurs
Examples of browser events are
resize - When a browser window has resized this event it is triggered and the layout is adjusted.
onmousemove - This event is fired when the mouse pointer is moved to calculate the new coordinate values of the mouse pointer.
Synthetic events - Events created and dispatched by the programmer are called synthetic events. These are custom events.
Synthetic events are created using the Event constructor. The syntax for synthetic events is as follows
Code - custom event
Output - custom event
For an element in order to respond to various action, you need to add an event listener to that element.
addEventListener() method is used to add an event listener
Code - add event listener
Output - add event listener
removeEventListener() method is used to remove an event listener
Both the above methods have the same syntax. It takes two parameters first is the event name and the second parameter is the callback function that needs to be executed.
There are many types of DOM events, some of them are network events, form events, storage events, etc. The most important of them are keyboard events and mouse events. We will look into these both using some examples.
Keyboard events :
There are three events in this category
- keydown - when the key is pressed.
- keypress- when the key is pressed continuously (except shift, fn, and capslock)
- Keyup - When the key is released.
Code - keyboard events
Output - keyboard events
In the example, you can notice that when I hold ctrl-left the keydown event is triggered when I release the ctrl-left keyup is triggered. The keypress is not triggered because it's not a continuous action, however, when I press A all the events are triggered.
You can refer to all other events here
I would recommend checking Event bubbling and capture on the MDN web docs it is very well explained.
Thank You for reading this article. Please give your feedback in the comments.