JavaScript Events and Event Listeners

As a part of the process of developing websites, one aim that you always strive to achieve is to make the end product interactive. This can primarily be done using events in JavaScript. This is because it is through events that web pages are able to respond to user inputs such as clicks and movements of the mouse, movement and strokes of the keyboard among many others. There are many ways in which these events can be managed with the help of JavaScript making it easier for developers to build interactive web applications. In this piece, we shall focus on what events are in JavaScript, how they work and how you can make use of events using event listeners to prevent users from interacting with your web page.

Events definition in Javascript

In regard to JavaScript, an event basically means every single interaction or action that the user or the browser makes use of within the webpage which mostly makes use of both the mouse and the keyboard. These events include such acts as:

- Clicking a button

- Moving the mouse

- Whenever a key on the keyboard is pressed

- Hovering an element

- Submitting a form

- Loading a web page

The events mentioned above are in terms of action that a web page will be able to respond to. When such actions occur, JavaScript can capture these events and execute specific code in response. This way, applications built in Java may be interactive and entertaining to use.

Types of Events

Various events occur in a web application depending on the actions performed by a user. Among the most frequent are the following:

- Click : Occurs when a mouse cursor clicks on a particular element.

- Mouseover : Occurs when the mouse pointer is positioned over an element.

- Mouseout : Occurs when the pointer is moved from over an element.

- Keydown : Occurs when a particular key on the keyboard is pressed

- Keyup : Occurs when a certain key of the keyboard is released.

- Submit : Occurs when a user submits a form.

- Load : Occurs when the page or an image is completely displayed.

- Focus : Occurs when an input field is clicked on.

The great advantage of these events is their effectiveness in ensuring user interactivity and the availability of multiple handling techniques in JavaScript

Event Listeners

In order to respond to events, JavaScript has event listeners. This is a function that waits for a certain action on an HTML tag. If an action takes place like you click on an element the function is executed. Event handlers of different types in JavaScript can be created as functions and attached to an HTML element as an event listener.

Adding The Listeners Of Events

In JavaScript, you can add event listeners to HTML elements with the `addEventListener()` method. With this method, you can tell the script which kind of events you are interested in, for example, "click" or "keydown", and which function will be executed when such an event occurs.

To provide an event listener the following steps should be followed:

addEventListener() Syntax

  element.addEventListener(event, function, useCapture); 
- `element`: The event listener will be added to that particular DOM element.

- `event`: The event type like "click" or "keydown".

- `function`: The function that should be executed as a listener for the event.

- `useCapture` (optional): It is a flag to tell whether during the capturing phase the event should be captured or not. The default value for this flag is `false`.

For example, to attach a click event listener to a button, you would write:

Adding Click Event Listener Example

  let button = document.getElementById("myButton");

button.addEventListener("click", function () {
alert("Button was clicked!");
});
In the above code, the event listener calls the function when there is a click on button with the ID `myButton` and the function shows an alert.

Event Propagation

An event at the top most document in the DOM tree and the event at the target and all the elements in between are what event propagations work on. There are two ways in which an event can propagate:

1. Capturing Phase : An event that travels down from the root down to the target element.

2. Bubbling Phase : A target element that travels all the way up the root.

In most cases, a bubbling phase is a type of event which gets executed first and this method only applies when there is a need to focus on a singular element in the event. So in layman terms an event in a tab will burn up as soon as the pointer hovers onto another element.

To illustrate, if the event from a child and parent target overlaps, the latter will always get their trigger later. Now here is a simple scenario, if you added two event listeners on the child and parent element then the child listener will go off first (during the bubbling phase).

The Event can be set off without alerting any other elements using the `stopPropagation()` method. This is handy when there is no need to merge other elements into the event and only a specific one suffices.


Event Object

An event object is created by the browser automatically as soon an event is initiated. The event object essentially has cool stuff about the type of event, which element caused it, and what else is related to the event.

You can have access to the event object if you declare it as a parameter in the event handler function. For instance:

Accessing Event Object

  element.addEventListener("click", function(event) {
console.log(event.type); // Will display the type of event which occurred, for example "click"
});
Some of the event object's properties which can be helpful are:

- `event.target`: A particular DOM element that raised the event is referred to as the event target.

- `event.clientX` and `event.clientY`: Mouse position in pixels with respect to the viewport.

- `event.key`: During a keyboard event, this is the key that was pressed.

Removing Event Listeners

Removing an event listener that has been added is sometimes required and JavaScript gives you the possibility to do so through the use of the `removeEventListener()` method. Just like its counterpart `addEventListener()`, `removeEventListener()` accepts the same parameters: the specific event and the callback.

For instance, if you need to delete a click event listener that has been previously assigned, you would write something like this:

Removing Event Listener Example

  button.removeEventListener("click", myFunction); 
Make sure to note that the one passed to `removeEventListener` must be identical to the same one that was passed to `addEventListener`. This explains why anonymous functions can't be removed in this way.

Event Delegation

The event delegation pattern is a useful pattern in making it easier to deal with events on several elements. Instead of attaching separate event listeners to each one of the elements, it is possible to attach a single event listener to a parent element. This parent element will receive events from its child elements and it is therefore possible to handle events in a lot of elements with a single event listener.

For instance, if there is a list of items and there is a need to detect when each item is clicked, instead of setting an event listener on every `<li>` element, an event listener can be placed on the outsourcing `<ul>` tag.

Event Delegation Example

  let list = document.getElementById("myList");

list.addEventListener("click", function(event) {
if (event.target.tagName === "LI") {
alert("Item clicked: " + event.target.textContent);
}
});
Related Articles