Skip to main content

Events

An event is a signal from the browser that something has happened on a web page. Events are used to react to user actions and execute code linked to a specific event. There are many types of events: mouse, keyboard, form elements, image loading, clipboard, CSS animation or transition stage change, window resizing, etc.

One action can trigger multiple events. For example, a click calls first mousedown, then mouseup and click. In cases where one action generates several events, their order is fixed. That is, handlers will be called in the following order: mousedown → mouseup → click.

In order for an element to react to user actions, it needs an event listener (handler). That is, a function that will be called as soon as the event occurs.

addEventListener() method

Adds an event listener to an element.

element.addEventListener(event, handler, options);
  • event is event name, a string, for example "click".
  • handler is a callback that will be called when the event occurs.
  • options is an optional parameter object with advanced options.
const button = document.querySelector(".my-button");

button.addEventListener("click", () => {
console.log("Button was clicked");
});

For a callback, you can (and should) use a separate function and pass a reference to it. A named function improves the readability of your code.

const button = document.querySelector(".my-button");

const handleClick = () => {
console.log("Button was clicked");
};

button.addEventListener("click", handleClick);

One element can have as many event handlers as you need, including events of the same type. Callback functions will be called in the order they are registered in the code.

removeEventListener() method

Removes an event listener from the element. The arguments are the same as for the addEventListener() method.

element.removeEventListener(event, handler, options);

To delete, you need to pass a reference to the callback that was assigned in addEventListener(). In this case, a separate function is used for callbacks and passed by name (reference).

Keyword this

If the callback is a function that uses this, by default the context inside it will refer to the DOM element with the listener.

const mango = {
username: "Mango",
showUsername() {
console.log(this);
console.log(`My username is: ${this.username}`);
},
};

const btn = document.querySelector(".js-btn");

// ✅ It works
mango.showUsername();

// ❌ this will refer to button if showUsername is used as callback
btn.addEventListener("click", mango.showUsername); // it does not work

// ✅ Do not forget to bind the context of the object methods
btn.addEventListener("click", mango.showUsername.bind(mango));