Listen for events in Javascript

Roseakoth
2 min readDec 14, 2020

--

Have you ever wondered when you click on a button on a web page, something happens. The most common scenario is when you see a popup message “Submitted successfully” after you insert your details on a form with just a click of a button. Well in this article, you will know what happens behind the scenes. Stay tuned!.

We want our users to be able to interact with our content by reacting to DOM events. When a user clicks a button, types in a text field or selects an option in a dropdown menu, an event is triggered, and by listening for that event, we can execute code to react to it.

What is an Event?

Events are actions that happen when a user interacts with the page — like clicking an element, typing in a field, or loading a page. The browser notifies the system that something has happened, and that it needs to be handled. It gets handled by registering a function, called an event handler, that listens for a particular type of event.

The browser detects a change, and alerts a function (event handler) that is listening to a particular event. These functions then perform the actions as desired.

Here are a few examples of HTML events we can listen for:

  • the user clicks the element
  • the user moves the mouse over the element
  • the user presses a key a form is submitted
  • the content of a form input is changed

Let’s have a look at how to react to these events such as listening to an event.

addEventListener()

We react to an event emitted by a DOM element by adding an event listener to that element. A listener is a function that will be executed every time the chosen event is emitted. The addEventListener() method takes two arguments: the event to listen for and the function to be executed when that event is emitted. Let's start with an example: adding a click listener to a button.

Here is a line of code that changes that adds two classes to the header, hence changing the header background to blue.

blueButton.addEventListener(‘click’, () => { header.classList.add(‘blue-background’, ‘text-white’);});

Different types of events

Here are some common events — onclick dblclick mousedown mouseup mousemove keydown keyup touchmove touchstart touchend onload onfocus onblur onerror onscroll

--

--

Roseakoth

Frontend developer. Technical writer. Shark mindset.