INSTACK 360

JavaScript Events & Event Listeners

Make your web pages interactive by listening to user actions like clicks, keystrokes, and form submissions.

Advanced 5 min read

What are Events?

HTML events are "things" that happen to HTML elements. When JavaScript is used in HTML pages, JavaScript can "react" on these events. Examples include: a mouse click, a web page loading, or a form submission.

addEventListener()

The addEventListener() method attaches an event handler to the specified element without overwriting existing event handlers.

const button = document.querySelector("#myBtn");

button.addEventListener("click", function() {
  alert("Button was clicked!");
});

The Event Object

When an event occurs, the browser creates an event object, puts details into it and passes it as an argument to the handler.

document.addEventListener("keydown", function(event) {
  console.log("Key pressed: " + event.key);
});

Event Bubbling

When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors. To stop this, use event.stopPropagation().