DEV Community


Javascript Events

Stephanie Opala
Front-end Developer
・1 min read

An event is an occurrence which when triggered, an action is supposed to be taken.
Examples of events include;
The click of a button.
A change in the input field.
A webpage finishes loading.
A form is submitted.

An event listener listens out for the event happening and the event handler is the code that runs in response to it happening. Each event has an event handler(a block of code) which runs when an event fires.

When a mouse clicks on the heading, change the font color to blue.

h1 id=”header1”>Welcome to my blog!</h1>
Enter fullscreen mode Exit fullscreen mode
const heading = document.getElementById(“header1”)

heading.addEventListener(“click”, function(event) { = “blue”;
Enter fullscreen mode Exit fullscreen mode

In the example above, we use getElementById to 'grab' the element with the id(header1).
.addEventListener() is a method.
"click" is the name of the event that we are listening for.
Upon clicking the element, the event is triggered which executes the line of code.

Discussion (2)

raddevus profile image

This is a nice short example of a JS event handler.

I believe another term for these are HTML DOM (Document Object Model) events. Because really the DOM raises the events and we actually capture (handle) them with event handlers in JavaScript.

I've been trying to switch my code from




because it is more descriptive of the query selectors.

Do you ever use document.querySelector()? Just curious.

stephanieopala profile image
Stephanie Opala Author

Thanks for your input.
And yes, I also use document.querySelector()