Event Registration - Part 1

Event Registration - Part 1

All about registering a DOM event

What

Well, you have created an awesome web page with HTML and CSS. It is sleek, rich, and responsive to different screen sizes and resolutions as well. Users get attracted to it due to the perfect color palette and effective typography.

But it is not enough. You want your users to interact with the page and have an engaging experience. Now some of it can be achieved with CSS and HTML. But Javascript DOM API provides a more intuitive way to create an engaging experience.

DOM API gives you a solution to listen to several different interactions made by a user and/or by a browser and respond to them the way to wish.

It is called DOM EVENTS .

In a developer's language, a DOM event is a mechanism to listen to an event and execute a piece of code in response. We don't need to worry either about detecting different events or executing the code in response to them. All modern browsers have sophisticated ways of detecting events and executing the code we provide. All we have to do is to REGISTER an event.

Registering an event

In order to register for an event, we have to specify 3 things

  • The thing on which event is expected to occur (usually HTML element)
  • Which event we want to listen to (event type)
  • Piece of code to execute once that event occurs (callback)

Methods

There are different methods to register for an event. Some are easy to implement while some provide more options and control over behavior. Depending upon our requirements, we need to decide which one to use. But by the collective experience of the developer community, there are some recommendations which we will cover soon.

We can register an event using one of the following.

  • HTML attribute
  • DOM property
  • EventTarget

1. HTML attribute

One of the simplest methods by far is to use the HTML attribute.

<button onclick="handleClick()"> Click </button>

If we tally this snippet with the registration steps mentioned before then we see that

  1. We wish to register an event on the BUTTON element.
  2. We wish to listen to a CLICK event.
  3. We wish to invoke the handleClick() function once the click event occurs on the button.

It is as simple as that.

The HTML attribute must be written in a specific format. It should start with the string 'on', followed by the event name which is 'click' in this case.

e.g. onchange, onfocus, onkeypress, etc.

The value assigned to this attribute should be a Javascript expression in string form. People coming from React or Angular backgrounds may find this confusing as we pass in the function references as event handlers over there.

But here we need to pass a string that is evaluated as a Javascript expression. These are few examples of what you can pass as value.

<button onclick="alert('button clicked');"> Click </button>
<button onclick="console.log('button clicked');"> Click </button>

Pros

  • Simple to use
  • Event handler function can access the event object by default. Note: it has to be the string 'event'. You cannot use other names for it. e.g.
<input onchange="alert(event.type)"/>

Cons

  • HTML gets polluted with business logic. It is recommended to keep the UI and the logic separated.
  • It is not possible to have multiple event handlers for the same event type.
  • This method does not allow to pass configuration options. (Config options are explained in addEventListener)
  • It is generally considered bad practice to use this method for production code.

2. DOM Property

Another simpler way of registering an event is using a DOM property.

<button id="button">Click</button>
// get reference to the button
const button = document.getElementById('button');
// register click event as a DOM property
button.onclick = function() {
  alert('button clicked');
};

Pros

  • Simple to use
  • We have a clear separation of UI and logic.

Cons

  • Same as the HTML attribute method.

3. EventTarget

EventTarget is an interface in DOM API that provides us with addEventListener/removeEventListener method. This is by far the neatest and most effective way to register for an event. It also provides us with configuration options that we can use to customize how and when an event should be handled.

3.1 addEventListener

There are different ways in which you can use addEventListener.

addEventListener(type, callback)

// get a reference to the element
const button = document.getElementById('button');
button.addEventListener('click', function(event) { 
  alert('button clicked');
});

In this example, we are trying to register the CLICK event on the button. We are providing an anonymous function to execute which receives an event object as an argument.

addEventListener(type, callback, useCapture)

// get a reference to the element
const button = document.getElementById('button');
// pass 3rd argument as true
button.addEventListener('click', function(event) { 
  alert('button clicked');
}, 
true);

If we pass a boolean value as 3rd parameter, then the event is registered for either the CAPTURE phase(true) or the BUBBLE phase (false) based on its value.

addEventListener(type, callback, optionsObject)

// get a reference to the element
const button = document.getElementById('button');
// pass 3rd argument as options object
button.addEventListener('click', function(event) { 
  alert('button clicked');
}, 
{
  capture: true,
  once: true,
  passive: true
});

We can also pass an object as 3rd argument. These properties can be explained as

  • capture: This is the same as useCapture.
  • once: If set then the event is invoked only once.
  • passive: This is used to set a passive listener. This is useful to avoid scroll jank on touch devices. For more information visit this link.

Pros

  • Most effective way of registering an event listener.
  • Can register multiple types of events for the same element.
  • Can register multiple handlers for the same type of event for the same element.
  • Can remove event listener with removeEventListener.
  • Can provide config options with useCapture / options object.

Cons

  • Verbose.
  • Matching of listeners for removeEventListener is tricky.

3.2 removeEventListener

This method is used to remove the event listener registered via addEventListener (only). The signature of removeSignature is exactly the same as addEventListener. Thus you can pass all values to removeListener which you can pass to addEventListener.

Matching event listeners

Registering an event with addEventListener and removing the same event with removeEventListener are two separate actions.

You must be wondering how removeEventListener knows which event listener to remove. There are rules to match an event listener.

The following arguments of addEventListener should match with that of removeEventListener in order for removeEventListener to work.

  • type
  • callback function (Both should be the same function by reference)
  • useCapture | capture (Boolean value of either should match)

References

Finally

With this, you should feel a little comfortable registering events to an element. The best way to solidify what you have read is by trying it out by yourself. In the next article, we are going to take our understanding about event registration to next level. We are going to try few tricky situations to gain more insights into DOM events.

Stay tuned...