Event & Event listener

Event is an important part of a website. It gives the user a sense that the site is 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?

An event is an action that happens when we manipulate a page.

For example, a “click” event happens when we click a button. It also happens when we type text into a 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 the 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

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

So when we listen to an event and 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);
}