

Here's the relevant JavaScript: let button = document.querySelector('#button') When a user clicks the button, a message is displayed. This is a simple example I made which shows you addEventListener() in action. By default, it's set to false which means that the innermost HTML event handler is executed first (bubbling phase).ĪddEventListener() Code Example Simple example demonstrating addEventListener() In the case of nested HTML elements (such as an img within a div) with attached event handlers, this value determines which event gets executed first.
#Addeventlistener keyup javascript full#
For the curious, here's a full list of HTML DOM events. We already mentioned load and click events. event: a string that specifies the name of the event.
#Addeventlistener keyup javascript how to#
This element exists as part of the Document Object Model (DOM) and you may wish to learn about how to select a DOM element. target: the HTML element you wish to add your event handler to.Here's the syntax: target.addEventListener(event, function, useCapture) 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. JavaScript provides an event handler in the form of the addEventListener() method. This way, you can set up code to react to events as they happen on the fly. In these scenarios, you need an event handler to detect when an event happens. You also may not know when an event will happen, especially if it is user generated. Many events can happen once, multiple times, or never. If a user clicks a button on a page, then a click event has happened. They play an important role as they can cause elements of a web page to change dynamically.įor example, when the browser finishes loading a document, then a load event occurred. Understanding Events and Event HandlersĮvents are actions that happen when the user or browser manipulates a page. This tutorial shows you how you can implement addEventListener() in your code.

The JavaScript addEventListener() method allows you to set up functions to be called when a specified event happens, such as when a user clicks a button.
