Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is an event handler in JavaScript

A Glimpse into Event Handlers in JavaScript

Event handlers are akin to attentive bodyguards, always looking out for specific occurrences or 'events' and reacting to them. In the context of JavaScript, events can be anything from a click of the mouse to a press of a keyboard key. When such an event occurs, an event handler springs into action, executing a block of code designed to respond to that event.

Understanding Events

To fully appreciate event handlers, we must first understand events. In the digital realm, events are user interactions or browser incidents. User interactions can be clicking a button, hovering over a link, dragging and dropping an object, pressing a key, and more. Browser incidents, on the other hand, can be the page finishing loading, the form being submitted, or an error occurring on the page.

Consider events as the 'what' and event handlers as the 'so what'. When 'what' happens (event), 'so what' do we do (event handler)?

Dive into Event Handlers

Event handlers are simply functions (a block of code) that are called in response to a specific event. These handlers give life to our web pages, making them interactive and responsive to user actions.

Here's a simple example of an event handler in JavaScript:

button.addEventListener('click', function() {
  alert('Button was clicked!');
});

In this example, the addEventListener method is used to attach a click event handler to a button. When the user clicks the button, an alert box pops up with the message 'Button was clicked!'.

Different Ways to Implement Event Handlers

Inline Event Handlers

An inline event handler is one where the handler (function) is directly written within the HTML element that it affects.

Here's an example:

<button onclick="alert('Button was clicked!');">Click me</button>

This method is easy to implement but not commonly used in modern web development due to its limitations. It can become messy with complex JavaScript code, and it also violates the principle of 'Separation of Concerns', which advocates for keeping HTML (markup), CSS (presentation), and JavaScript (behavior) separate.

Traditional/DOM Level 0 Event Handlers

Here, the event handler is a property of the HTML element and contains the function to be executed when the event occurs.

Example:

var button = document.querySelector('button');
button.onclick = function() {
  alert('Button was clicked!');
};

One downside of this method is that you can only attach one function to an event per element. If you try to attach another function to the same event, it will override the previous one.

Advanced/DOM Level 2 Event Handlers

This is the most modern and recommended way of handling events. In this method, we use addEventListener() to register the event handler.

Example:

var button = document.querySelector('button');
button.addEventListener('click', function() {
  alert('Button was clicked!');
});

The advantage of this method is you can attach multiple functions to the same event on the same element without overriding any existing event handlers.

Event Handler in Action

Let's create an interactive web page where the background color changes each time the user clicks a button.

<button id="colorButton">Change Color</button>
var button = document.querySelector('#colorButton');
var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];

button.addEventListener('click', function() {
  document.body.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
});

Each time the button is clicked, a random color is selected from the array and applied as the background color of the body.

Conclusion: The Symphony of Web Interactivity

To understand event handlers is to understand the orchestra of interactivity happening on the web. They are the conductors ensuring that the right action follows the right cue. As you venture deeper into the world of JavaScript, consider event handlers as your trusty sidekicks, always ready to respond to events and bring a pulse to your static web pages. With a solid understanding of event handlers, you'll be well on your way to creating engaging, interactive web experiences.