DEV Community

Cover image for Events Handling In JavaScript
Akinnimi Stefan Emmanuel
Akinnimi Stefan Emmanuel

Posted on

Events Handling In JavaScript

Events are notifications of changes in the operating system or browser environment fired inside the browser window. Web pages may react effectively to changes thanks to the event handler code that programmers can design and run whenever an event occurs.

Event Types

  1. Mouse Events
    Click: This occurs when a mouse button is clicked (pressed and released) on an element.
    dblclick: This occurs when a mouse button is double-clicked on an element.
    mousedown: This occurs when a mouse button is pressed down on an element.
    mouseup: This occurs when a mouse button is released on an element.
    mousemove: This occurs when the mouse pointer moves over an element.
    mouseenter: This occurs when the mouse pointer enters an element.
    mouseleave: This occurs when the mouse pointer leaves an element.
    mouseover: This occurs when the mouse pointer moves over an element or its child elements.
    mouseout: This occurs when the mouse pointer moves out of an element or its child elements.
    contextmenu: This occurs when the right mouse button is clicked on an element, opening the context menu.

  2. Keyboard Events
    keydown: This occurs when a keyboard key is pressed down.
    keyup: This occurs when a keyboard key is released.
    keypress: This occurs when a keyboard key is pressed and released.

  3. Form Events
    submit: This occurs when a form is submitted.
    reset: This occurs when a form is reset.
    input: This occurs when the value of an input element changes (e.g., when typing into a text field).
    focus: This occurs when an element receives focus (e.g., by clicking on an input field).
    blur: This occurs when an element loses focus (e.g., clicking away from an input field).
    change: This occurs when the value of a form element changes (e.g., selecting a different option in a dropdown).

  4. Document and Window Events
    load: This occurs when a web page or an external resource (e.g., an image) has finished loading.
    unload: This occurs when the user navigates away from a web page or closes the window.
    resize: This occurs when the browser window is resized.
    scroll: This occurs when the user scrolls the webpage.
    DOMContentLoaded: This occurs when the HTML document has been completely loaded and parsed, even if external resources (like images) are still loading.

  5. Drag and Drop Events
    dragstart: This occurs when an element is dragged.
    dragend: This occurs when the dragging of an element is finished.
    dragenter: This occurs when a dragged element enters a drop target.
    dragleave: This occurs when a dragged element leaves a drop target.
    dragover: This occurs when a dragged element is over a drop target.
    drop: This occurs when a dragged element is dropped on a drop target.

These event types allow programmers to create interactive and responsive web applications by listening and responding or acting on the actions on the web pages.

Methods Of Attaching an Event Handler to HTML Elements

To react to an event in your browser, you attach an event handler to it. This event handler fires when the event is triggered.

a. Inline Event Handlers

You can add event handlers directly to HTML elements using inline event attributes. For example:

inline event handler

In this example, the 'onclick' attribute specifies that the 'alert' message should be shown on the web page when the button is clicked. While this approach is simple, it's generally not recommended for larger applications due to concerns about separation of concerns and maintainability.

b. DOM Level 0 Event Handlers

You can directly assign event handler functions to DOM elements using JavaScript. For example:

DOM level event handlers

This method is straightforward but allows only one event handler per event type for a given element.

c. addEventListener():

The addEventListener() method is the preferred way to attach event handlers in modern JavaScript. It allows you to add multiple event listeners to an element, ensuring better compatibility and flexibility. For example:

Add event listener method

Whenever the button is clicked, an alert message is printed to the console.

mouseover event type

Whenever the mouse is moved over the div, the color of the div changes to purple.

Removing an Event Listener

The removeEventListener() function can be used to delete an event handler that has already been added using the addEventListener() method. For example, this would remove the changeColor event handler.

Removing an event listener

Removing outdated event handlers from small, basic systems is not required, but it can increase productivity for bigger, more sophisticated projects. You can also have the same button execute multiple actions under different conditions by adding or removing event handlers, which is another benefit of this feature.

Event objects

There are occasions when a parameter with a name like an event, evt, or e is supplied inside an event handler function. This is referred to as the event object, and it is often supplied to event handlers to offer more functionality and details.
An event object is a javascript object containing information about an event when triggered in the DOM.

Events objects

In the code snippet above, notice the event type has changed to "keydown" meaning a key must be pressed to trigger this event.

Here you can see we are including an event object, ‘events’ in the function, and in the function we are setting the events key to q, which means the letter q has to be pressed down on the keyboard to “console.log” the sentence to the console.

You can also get the target using the method "event.target" which is the DOM element that triggered the event.

event target method

Common methods of the event objects include:

event.key
event.target
event.type
event.preventDefault
event.currentTarget
event.stopPropagation
event.stopImmediatePropagation

In summary, the event object is a crucial tool for handling events in JavaScript. It provides access to specific event data and allows you to control the event's behavior using different methods.

Event Propagation

Event propagation refers to the order in which events are handled as they propagate through the document object model (DOM).

There are two phases of event propagation in the DOM
a. Capturing Phase
b. Bubbling Phase

a. Capturing Phase (outside to inside):

In the capturing phase, the events start from the root of the DOM tree (window object) and move downward towards the target element. During this phase, any registered event listeners on the elements above the target element are triggered before the event reaches the target element.

To specify that you want to listen for events during the capturing phase, you can pass true as the third argument to the addEventListener() method:

syntax for capturing phase in event propagation

let's add event propagation to our HTML elements below
HTML
The HTML structure contains two elements, the heading and the button.

HTML structure for event propagation

JavaScript
To understand the capturing phase properly, let's add event listeners to the window and the document objects.

Capturing phase

Output

In the code snippet above, the button is the target, but the event propagation started from the window all the way down before getting to the target.

output from the capturing phase

From the output above, the capturing phase starts from the root Dom (window) after clicking on the button (the target) and then moves downwards to the button.

b. Bubbling Phase (inside to outside)

This is the opposite of the capturing phase; the events start from the target all the way up to the root Dom (window object).
The bubbling phase is the more commonly used event propagation phase, as it often aligns with the way you structure your HTML and want events to be handled. By default, when you use addEventListener(), events are registered for the bubbling phase:
There is no need for the third parameter because the event handler is by default in the bubbling phase.

bubbling phase syntax

You can also add the third parameter, which is "false" to your code

adding the third parameter

Still using the same HTML structure above, let's tweak our JavaScript code a bit by changing the third parameter.

bubbling phase

The JavaScript still has the same code; we just changed the true parameter to false. This will change the event propagation from the capturing phase (UP) to the bubbling phase (DOWN).

OUTPUT

output of the bubbling phase
The event propagation started from the target (button) all the way up to the window object.

Event Delegation

Event delegation allows you to attach a single event listener to a parent element that adds it to all of its present and future descendants that match a selector.

HTML structure

HTML structure

JavaScript

JavaScript structure

Output

event delegation output

The event listener is added to the parent element of the list, which has a class of sports, and then it adds the listener to all of its child elements. Instead of adding the event listener to each child element of sports, this can significantly reduce the number of event listeners in your application and improve performance.

In conclusion, event handling plays a pivotal role in modern software development and user interface design. Whether you're developing a web application, a desktop program, or a mobile app, effectively managing and responding to events is essential for creating a seamless and interactive user experience.
Throughout this article, we've explored the fundamental concepts of event handling, including event types, event listeners, event propagation, and event delegation. We've also discussed best practices for event handling, such as using event delegation to improve performance and maintainability and ensuring accessibility by providing keyboard and screen reader support.

Top comments (0)