JavaScript events explained with examples

JavaScript events explained with examples

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

1.What is an Event?

2.Add and remove an eventlistener

3.Types of events

What is an Event?

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

custom event code

Output - custom event

custom event output

Add and remove an event listener

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

add event listener

Output - add event listener

Alt Text

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.

Types of events.

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

  1. keydown - when the key is pressed.
  2. keypress- when the key is pressed continuously (except shift, fn, and capslock)
  3. Keyup - When the key is released.
Code - keyboard events

keyboard events

Output - keyboard events

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.