Event & Event listener

Event is an important part of a website. It gives the user a sense that the site is actually communicating.

In this article, we will learn about an event and how to add an event listener to a webpage.

I. What is an event?

Event is an action that happens when we manipulate a page.

For example, when we click a button, a “click” event happens. It also happens when we type text into textfield or move the cursor on something.

II. addEventListener()

An event listener allows us to call functions when a specified event happens.

We use a method addEventListener() with the syntax:

target.addEventListener(event, function, useCapture)
  • target: This is the element you need to add Event Listeners to. (Using DOM Selector).
  • event: The types of events such as click, mouseover, etc.
  • function: The function you need to add
  • useCapture: This parameter is optional. It’s a boolean value specifying whether to use event bubbling or event capturing.

Example

const button = document.querySelector(".btn");

button.addEventListener("click", function(event) {
  alert("Hello World");;
})

// OR
button.addEventListener("click", event => alert("Hello World"));

We can also replace the function:

const button = document.querySelector(".btn");

button.addEventListener("click", buttonClick);

function buttonClick() {
  alert("Hello World");
}

III. Event types

We have different event types:

  • dblclick: Double click
  • mousedown: As soon as we click down, event fires
  • mouseup: Click and release the mouse, event fires
  • mouseenter: Event fires when we enter the parent element
  • mouseover: Event fires when we hover mouse for any inner element
  • mouseleave: Event fires when mouse out the parent element
  • mouseout: Event fires when mouse out for any inner element
  • mousemove

IV. Event parameter

The event is an object containing information about the action that just happened.

So when we listen for an event and we run a function, we can pass in an event parameter. It’s optional.

We can console.log the event (e) and see the event object and its properties.

const button = document.querySelector(".btn");

button.addEventListener("click", buttonClick);

function buttonClick(e) {
  console.log(e);
}