Javascript Events!

Faizah Ahsan
2 min readJan 2, 2021

Javascript in the browser uses an event-driven programming model. When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc. Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set of events which can trigger JavaScript Code. There are various types of events. In this blog, I will talk about a few of them.

What are Event handlers?

You can respond to any event using an event handler, which is a function that’s called when an event occurs. You can register multiple handlers for the same event, and they will all be called when that event happens.

JavaScript offer three ways to register an event handler:

Inline event handlers

This style of event handlers is very rarely used today, due to its constraints, but it was the only way in the JavaScript early days:

Example:

<a href="site.com" onclick="dosomething();">A link</a>

DOM on-event handlers

The on-evetn handlers are a group of properties offered by DOM elements (both interactive — such as links, buttons, images, forms — and not), the base document itself, and so on, to help manage how that element reacts to events like being clicked, detecting pressed keys, getting focus, etc. — and they are usually named accordingly, such as onclick, onkeypress, onfocus, etc.

Using addEventListener()

The addEventListener() is an inbuilt function in JavaScript, which takes the event to listen for, and a second argument to be called whenever the described event gets fired. Any number of event handlers can be added to a single element without overwriting existing event handlers.This handler can be attached to a specific HTML element you wish to monitor events for, and the element can have more than one handler attached.

--

--

Faizah Ahsan

Junior Full-Stack Web Developer. Looking for opportunities!