DEV Community

Steven Gutierrez
Steven Gutierrez

Posted on

A Quick Guide to Event Listeners

Event listeners are a useful feature built into JavaScript that showcases how dynamic web pages can be. But the question is...

What are Event Listeners?

An Event Listener is a procedure in JavaScript that waits for an event to occur. This event can be caused by the Document, Web Browser, Object, or Element. The action created by the Event Listener is done asynchronously, which allows for a quicker run time and creates a more exciting application.

How are Event Listeners used?

In order to use Event Listeners they must be applied to an object or document element that is the target of the event.Once applied the Event Listener will be invoked automatically by the browser. For example:

let form = document.querySelector('form')
form.addEventListener()
Enter fullscreen mode Exit fullscreen mode

In this case, form is the element that we are targeting.

There are two ways Event Listeners can be applied to a web page:

  • onXYZ: The first way, although not as common, is done by directly setting the property of the object or element. This is done by adding .on followed by the event type to the desired element. For example:
let form = document.querySelector('form')
form.onsubmit = callbackFunction;
Enter fullscreen mode Exit fullscreen mode

*However, there is a key issue with this kind of programming as it assumes you will only register one handler for each type of event. So if you ever need to add more handlers the previously registered handlers will be overwritten.

  • .addEventListener: The second, and most common way, is using the .addEventListener() method. Much like the previous example, this method is applied to an object or element. Then two parameters are needed to define the method. The first is the event type ex: click. Second is a callback function that will handle the event after an action occurs.
let form = document.querySelector('form')
form.addEventListener('submit',callbackFunction);
Enter fullscreen mode Exit fullscreen mode

*Side Note: You can also set the event handler attribute to the property of a specific HTML element directly on your HTML file. However, this can cause some issues in your code later on.

Event Types:

There are many even types including: onClick submit mouseOver keyDown. Each has its own unique use, for a more comprehensive list see EventTypes.

Top comments (0)