• Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

EventTarget: addEventListener() method

Note: This feature is available in Web Workers .

The addEventListener() method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.

Common targets are Element , or its children, Document , and Window , but the target may be any object that supports events (such as IDBRequest ).

Note: The addEventListener() method is the recommended way to register an event listener. The benefits are as follows:

  • It allows adding more than one handler for an event. This is particularly useful for libraries, JavaScript modules, or any other kind of code that needs to work well with other libraries or extensions.
  • In contrast to using an onXYZ property, it gives you finer-grained control of the phase when the listener is activated (capturing vs. bubbling).
  • It works on any event target, not just HTML or SVG elements.

The method addEventListener() works by adding a function, or an object that implements a handleEvent() function, to the list of event listeners for the specified event type on the EventTarget on which it's called. If the function or object is already in the list of event listeners for this target, the function or object is not added a second time.

Note: If a particular anonymous function is in the list of event listeners registered for a certain target, and then later in the code, an identical anonymous function is given in an addEventListener call, the second function will also be added to the list of event listeners for that target.

Indeed, anonymous functions are not identical even if defined using the same unchanging source-code called repeatedly, even if in a loop .

Repeatedly defining the same unnamed function in such cases can be problematic. (See Memory issues , below.)

If an event listener is added to an EventTarget from inside another listener — that is, during the processing of the event — that event will not trigger the new listener. However, the new listener may be triggered during a later stage of event flow, such as during the bubbling phase.

A case-sensitive string representing the event type to listen for.

The object that receives a notification (an object that implements the Event interface) when an event of the specified type occurs. This must be null , an object with a handleEvent() method, or a JavaScript function . See The event listener callback for details on the callback itself.

An object that specifies characteristics about the event listener. The available options are:

A boolean value indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. If not specified, defaults to false .

A boolean value indicating that the listener should be invoked at most once after being added. If true , the listener would be automatically removed when invoked. If not specified, defaults to false .

A boolean value that, if true , indicates that the function specified by listener will never call preventDefault() . If a passive listener does call preventDefault() , the user agent will do nothing other than generate a console warning.

If this option is not specified it defaults to false – except that in browsers other than Safari, it defaults to true for wheel , mousewheel , touchstart and touchmove events. See Using passive listeners to learn more.

An AbortSignal . The listener will be removed when the given AbortSignal object's abort() method is called. If not specified, no AbortSignal is associated with the listener.

A boolean value indicating whether events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree. Events that are bubbling upward through the tree will not trigger a listener designated to use capture. Event bubbling and capturing are two ways of propagating events that occur in an element that is nested within another element, when both elements have registered a handle for that event. The event propagation mode determines the order in which elements receive the event. See DOM Level 3 Events and JavaScript Event order for a detailed explanation. If not specified, useCapture defaults to false .

Note: For event listeners attached to the event target, the event is in the target phase, rather than the capturing and bubbling phases. Event listeners in the capturing phase are called before event listeners in any non-capturing phases.

A Firefox (Gecko)-specific parameter. If true , the listener receives synthetic events dispatched by web content (the default is false for browser chrome and true for regular web pages). This parameter is useful for code found in add-ons, as well as the browser itself.

Return value

None ( undefined ).

Usage notes

The event listener callback.

The event listener can be specified as either a callback function or an object whose handleEvent() method serves as the callback function.

The callback function itself has the same parameters and return value as the handleEvent() method; that is, the callback accepts a single parameter: an object based on Event describing the event that has occurred, and it returns nothing.

For example, an event handler callback that can be used to handle both fullscreenchange and fullscreenerror might look like this:

Safely detecting option support

In older versions of the DOM specification, the third parameter of addEventListener() was a Boolean value indicating whether or not to use capture. Over time, it became clear that more options were needed. Rather than adding more parameters to the function (complicating things enormously when dealing with optional values), the third parameter was changed to an object that can contain various properties defining the values of options to configure the process of removing the event listener.

Because older browsers (as well as some not-too-old browsers) still assume the third parameter is a Boolean, you need to build your code to handle this scenario intelligently. You can do this by using feature detection for each of the options you're interested in.

For example, if you want to check for the passive option:

This creates an options object with a getter function for the passive property; the getter sets a flag, passiveSupported , to true if it gets called. That means that if the browser checks the value of the passive property on the options object, passiveSupported will be set to true ; otherwise, it will remain false . We then call addEventListener() to set up a fake event handler, specifying those options, so that the options will be checked if the browser recognizes an object as the third parameter. Then, we call removeEventListener() to clean up after ourselves. (Note that handleEvent() is ignored on event listeners that aren't called.)

You can check whether any option is supported this way. Just add a getter for that option using code similar to what is shown above.

Then, when you want to create an actual event listener that uses the options in question, you can do something like this:

Here we're adding a listener for the mouseup event on the element someElement . For the third parameter, if passiveSupported is true , we're specifying an options object with passive set to true ; otherwise, we know that we need to pass a Boolean, and we pass false as the value of the useCapture parameter.

You can learn more in the Implementing feature detection documentation and the explainer about EventListenerOptions from the Web Incubator Community Group .

The value of "this" within the handler

It is often desirable to reference the element on which the event handler was fired, such as when using a generic handler for a set of similar elements.

When attaching a handler function to an element using addEventListener() , the value of this inside the handler will be a reference to the element. It will be the same as the value of the currentTarget property of the event argument that is passed to the handler.

As a reminder, arrow functions do not have their own this context .

If an event handler (for example, onclick ) is specified on an element in the HTML source, the JavaScript code in the attribute value is effectively wrapped in a handler function that binds the value of this in a manner consistent with the addEventListener() ; an occurrence of this within the code represents a reference to the element.

Note that the value of this inside a function, called by the code in the attribute value, behaves as per standard rules . This is shown in the following example:

The value of this within logID() is a reference to the global object Window (or undefined in the case of strict mode .

Specifying "this" using bind()

The Function.prototype.bind() method lets you establish a fixed this context for all subsequent calls — bypassing problems where it's unclear what this will be, depending on the context from which your function was called. Note, however, that you'll need to keep a reference to the listener around so you can remove it later.

This is an example with and without bind() :

Another solution is using a special function called handleEvent() to catch any events:

Another way of handling the reference to this is to use an arrow function, which doesn't create a separate this context.

Getting data into and out of an event listener

It may seem that event listeners are like islands, and that it is extremely difficult to pass them any data, much less to get any data back from them after they execute. Event listeners only take one argument, the Event Object , which is automatically passed to the listener, and the return value is ignored. So how can we get data in and back out of them? There are a number of good methods for doing this.

Getting data into an event listener using "this"

As mentioned above , you can use Function.prototype.bind() to pass a value to an event listener via the this reference variable.

This method is suitable when you don't need to know which HTML element the event listener fired on programmatically from within the event listener. The primary benefit to doing this is that the event listener receives the data in much the same way that it would if you were to actually pass it through its argument list.

Getting data into an event listener using the outer scope property

When an outer scope contains a variable declaration (with const , let ), all the inner functions declared in that scope have access to that variable (look here for information on outer/inner functions, and here for information on variable scope). Therefore, one of the simplest ways to access data from outside of an event listener is to make it accessible to the scope in which the event listener is declared.

Note: Although inner scopes have access to const , let variables from outer scopes, you cannot expect any changes to these variables to be accessible after the event listener definition, within the same outer scope. Why? Because by the time the event listener would execute, the scope in which it was defined would have already finished executing.

Getting data into and out of an event listener using objects

Unlike most functions in JavaScript, objects are retained in memory as long as a variable referencing them exists in memory. This, and the fact that objects can have properties, and that they can be passed around by reference, makes them likely candidates for sharing data among scopes. Let's explore this.

Note: Functions in JavaScript are actually objects. (Hence they too can have properties, and will be retained in memory even after they finish executing if assigned to a variable that persists in memory.)

Because object properties can be used to store data in memory as long as a variable referencing the object exists in memory, you can actually use them to get data into an event listener, and any changes to the data back out after an event handler executes. Consider this example.

In this example, even though the scope in which both the event listener and the interval function are defined would have finished executing before the original value of someObject.aProperty would have changed, because someObject persists in memory (by reference ) in both the event listener and interval function, both have access to the same data (i.e. when one changes the data, the other can respond to the change).

Note: Objects are stored in variables by reference, meaning only the memory location of the actual data is stored in the variable. Among other things, this means variables that "store" objects can actually affect other variables that get assigned ("store") the same object reference. When two variables reference the same object (e.g., let a = b = {aProperty: 'Yeah'}; ), changing the data in either variable will affect the other.

Note: Because objects are stored in variables by reference, you can return an object from a function to keep it alive (preserve it in memory so you don't lose the data) after that function stops executing.

Memory issues

In the first case above, a new (anonymous) handler function is created with each iteration of the loop. In the second case, the same previously declared function is used as an event handler, which results in smaller memory consumption because there is only one handler function created. Moreover, in the first case, it is not possible to call removeEventListener() because no reference to the anonymous function is kept (or here, not kept to any of the multiple anonymous functions the loop might create.) In the second case, it's possible to do myElement.removeEventListener("click", processEvent, false) because processEvent is the function reference.

Actually, regarding memory consumption, the lack of keeping a function reference is not the real issue; rather it is the lack of keeping a static function reference.

Using passive listeners

If an event has a default action — for example, a wheel event that scrolls the container by default — the browser is in general unable to start the default action until the event listener has finished, because it doesn't know in advance whether the event listener might cancel the default action by calling Event.preventDefault() . If the event listener takes too long to execute, this can cause a noticeable delay, also known as jank , before the default action can be executed.

By setting the passive option to true , an event listener declares that it will not cancel the default action, so the browser can start the default action immediately, without waiting for the listener to finish. If the listener does then call Event.preventDefault() , this will have no effect.

The specification for addEventListener() defines the default value for the passive option as always being false . However, to realize the scroll performance benefits of passive listeners in legacy code, modern browsers have changed the default value of the passive option to true for the wheel , mousewheel , touchstart and touchmove events on the document-level nodes Window , Document , and Document.body . That prevents the event listener from canceling the event , so it can't block page rendering while the user is scrolling.

Because of that, when you want to override that behavior and ensure the passive option is false , you must explicitly set the option to false (rather than relying on the default).

You don't need to worry about the value of passive for the basic scroll event. Since it can't be canceled, event listeners can't block page rendering anyway.

See Improving scroll performance using passive listeners for an example showing the effect of passive listeners.

Older browsers

In older browsers that don't support the options parameter to addEventListener() , attempting to use it prevents the use of the useCapture argument without proper use of feature detection .

Add a simple listener

This example demonstrates how to use addEventListener() to watch for mouse clicks on an element.

In this code, modifyText() is a listener for click events registered using addEventListener() . A click anywhere in the table bubbles up to the handler and runs modifyText() .

Add an abortable listener

This example demonstrates how to add an addEventListener() that can be aborted with an AbortSignal .

In the example above, we modify the code in the previous example such that after the second row's content changes to "three", we call abort() from the AbortController we passed to the addEventListener() call. That results in the value remaining as "three" forever because we no longer have any code listening for a click event.

Event listener with anonymous function

Here, we'll take a look at how to use an anonymous function to pass parameters into the event listener.

Notice that the listener is an anonymous function that encapsulates code that is then, in turn, able to send parameters to the modifyText() function, which is responsible for actually responding to the event.

Event listener with an arrow function

This example demonstrates a simple event listener implemented using arrow function notation.

Please note that while anonymous and arrow functions are similar, they have different this bindings. While anonymous (and all traditional JavaScript functions) create their own this bindings, arrow functions inherit the this binding of the containing function.

That means that the variables and constants available to the containing function are also available to the event handler when using an arrow function.

Example of options usage

Click the outer, middle, inner containers respectively to see how the options work.

Before using a particular value in the options object, it's a good idea to ensure that the user's browser supports it, since these are an addition that not all browsers have supported historically. See Safely detecting option support for details.

Event listener with multiple options

You can set more than one of the options in the options parameter. In the following example we are setting two options:

  • passive , to assert that the handler will not call preventDefault()
  • once , to ensure that the event handler will only be called once.

Improving scroll performance using passive listeners

The following example shows the effect of setting passive . It includes a <div> that contains some text, and a check box.

The code adds a listener to the container's wheel event, which by default scrolls the container. The listener runs a long-running operation. Initially the listener is added with the passive option, and whenever the checkbox is toggled, the code toggles the passive option.

The effect is that:

  • Initially, the listener is passive, so trying to scroll the container with the wheel is immediate.
  • If you uncheck "passive" and try to scroll the container using the wheel, then there is a noticeable delay before the container scrolls, because the browser has to wait for the long-running listener to finish.

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • EventTarget.removeEventListener()
  • Creating and triggering custom events
  • More details on the use of this in event handlers

Home » JavaScript DOM » Handling Events in JavaScript

Handling Events in JavaScript

Summary : in this tutorial, you will learn the various ways to perform event handling in JavaScript.

When an event occurs, you can create an event handler which is a piece of code that will execute to respond to that event. An event handler is also known as an event listener . It listens to the event and responds accordingly to the event fires.

An event listener is a function with an explicit name if you intend to reuse it or an anonymous function if you only use it once.

An event can be handled by one or multiple event handlers. If an event has multiple event handlers, all the event handlers will be executed when the event is fired.

There are three ways to assign event handlers.

1) HTML event handler attributes

Event handlers typically have names that begin with on , for example, the event handler for the click event is onclick .

To assign an event handler to an event associated with an HTML element, you can use an HTML attribute with the name of the event handler. For example, to execute some code when a button is clicked, you use the following:

In this case, when the button is clicked, the alert box is shown.

When you assign JavaScript code as the value of the onclick attribute, you need to escape the HTML characters such as ampersand ( & ), double quotes ( " ), less than ( < ), etc., or you will get a syntax error.

An event handler defined in the HTML can call a function defined in a script. For example:

In this example, the button calls the showAlert() function when it is clicked.

The showAlert() is a function defined in a separate <script> element, and could be placed in an external JavaScript file.

Important notes

The following are some important points when you use the event handlers as attributes of the HTML element:

First, the code in the event handler can access the event object without explicitly defining it:

Second, the this value inside the event handler is equivalent to the event’s target element:

Third, the event handler can access the element’s properties, for example:

Disadvantages of using HTML event handler attributes

Assigning event handlers using HTML event handler attributes is considered a bad practice and should be avoided as much as possible for the following reasons:

First, the event handler code is mixed with the HTML code, which will make the code more difficult to maintain and extend.

Second, it is a timing issue. If the element is loaded fully before the JavaScript code, users can start interacting with the element on the webpage which will cause an error.

For example, suppose that the following showAlert() function is defined in an external JavaScript file:

And when the page is loaded fully and the JavaScript has not been loaded, the showAlert() function is undefined. If users click the button at this moment, an error will occur.

2) DOM Level 0 event handlers

Each element has event handler properties such as onclick . To assign an event handler, you set the property to a function as shown in the example:

In this case, the anonymous function becomes the method of the button element. Therefore, the this value is equivalent to the element. And you can access the element’s properties inside the event handler:

By using the this value inside the event handler, you can access the element’s properties and methods.

To remove the event handler, you set the value of the event handler property to null :

The DOM Level 0 event handlers are still being used widely because of their simplicity and cross-browser support.

3) DOM Level 2 event handlers

DOM Level 2 Event Handlers provide two main methods for dealing with the registering/deregistering event listeners:

  • addEventListener() – register an event handler
  • removeEventListener() – remove an event handler

These methods are available in all DOM nodes.

The addEventListener() method

The addEventListener() method accepts three arguments: an event name, an event handler function, and a Boolean value that instructs the method to call the event handler during the capture phase ( true ) or during the bubble phase ( false ). For example:

It is possible to add multiple event handlers to handle a single event, like this:

The removeEventListener() method

The removeEventListener() removes an event listener that was added via the addEventListener() . However, you need to pass the same arguments as were passed to the addEventListener() . For example:

Using an anonymous event listener as the following will not work:

  • There are three ways to assign an event handler: HTML event handler attribute, element’s event handler property, and addEventListener() .
  • Assigning an event handler via the HTML event handler attribute should be avoided.

How to add an event handler in JavaScript

Adding multiple event handlers to the same element, adding an event handler to the window object, event bubbling and capturing.

To add an event handler to an HTML element, you can use the addEventListener() method of the element object.

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

Let us say you have the following button with an ID #clickMe :

To attach a click event handler to the above button, you can use the following example:

As you can see above, we first defined an event handler function and then use the addEventListener() method to attach it with the element.

The addEventListener() accepts up to three parameters. The first parameter is the name of the event you want to listen for, like click , change , mouseover , and so on. The second parameter is the function that you want to call when the event occurs. The third parameter is an optional boolean value indicating whether you want to use event bubbling or event capturing.

If you are not interested in reusing the event handler function, you could also use an anonymous function as an event handler:

The addEventListener() method allows you to add any number of events to the same HTML element, without overwriting existing events.

You can also add events of different types to the same element by using the addEventListener() method:

The addEventListener() method allows you to add event listeners to any DOM object like HTML elements, the HTML document, and the window object.

For example, here is an event listener that fires when the user scrolls the document:

Event bubbling and capturing are two ways of event propagation in the HTML DOM. Event propagation defines the order of elements when the event occurs.

Suppose you have a <button> element inside a <p> element, and the user clicks on the <button> element. Which element's click event should be handled first?

In capturing, the outermost element's event is handled first and then the inner. The <p> element's click event will be handled first, and then the <button> element's click event.

In bubbling, the innermost element's event is handled first and then the outer. The <button> element's click event will be handled first, and then the <p> element's click event.

By default, the addEventListener() 's third parameter value is false , that means it uses the bubbling propagation. To use capturing propagation instead, pass the third parameter as true :

✌️ Like this article? Follow me on Twitter and LinkedIn . You can also subscribe to RSS Feed .

You might also like...

  • Get the length of a Map in JavaScript
  • Delete an element from a Map in JavaScript
  • Get the first element of a Map in JavaScript
  • Get an element from a Map using JavaScript
  • Update an element in a Map using JavaScript
  • Add an element to a Map in JavaScript

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.

  • JavaScript, Node.js & Spring Boot
  • In-depth tutorials
  • Super-handy protips
  • Cool stuff around the web
  • 1-click unsubscribe
  • No spam, free-forever!

How to handle event handling in JavaScript (examples and all)

How to handle event handling in JavaScript (examples and all)

In this blog, I will try to make clear the fundamentals of the event handling mechanism in JavaScript, without the help of any external library like Jquery/React/Vue.

I will be explaining the following topics in this article:

  • The document and window objects, and adding Event Listeners to them.
  • The Event.preventDefault() method and it’s usage.
  • The Event.stopPropagation() method with an example.
  • How to remove an event listener from an element.

Document and window objects with Event Listeners

The Window object represents the tab. In case you are reading this blog on your corresponding browser, then your current tab represents the Window object.

The window object has access to such information as the toolbar, height and width of the window, prompts, and alerts. Let’s see how we can add an event listener (mousedown) to the window object and analyze some of its properties.

How to add the listener on the window object

The addEventListener method is the most preferred way to add an event listener to window , document or any other element in the DOM.

There is one more way called “on” property onclick, onmouseover, and so on. But is not as useful, as it does not allow us to add multiple event listeners on the same element. The other methods allow it.

An event object is passed as an argument (optional) to the handler which contains all the information related to the event (in our case, mousedown) on the window.

Open the developer tools (Inspect Element) on this page and copy paste the following code in the console panel and hit enter.

After that, you can go over to any section of the current tab and right click to see the console and the info related to this event, as shown below in the snapshot.

Note : If you go to any other tab and right click, then this event will not get fired as it belongs to this tab (Window object) only.

OkOuvlALsx7sPyDl7NJ2AfcjV7yCSoVpN2TK

The details of the mousedown event

In the next few lines, I will explain some of the important captured property corresponding to the mousedown event we just performed.

button : As this was the mousedown event, it will tell you the button you clicked. For the mouse, Left, middle, and right correspond to 0, 1, and 2 respectively. If you click the right button, you can see the value 2.

clientX and clientY : Position relative to the upper left of the content area (Viewport). Just analyze the value of these properties with the place you clicked, and you can see how they’re related. Even if you scroll down the page, these properties remain the same. ScreenX and ScreenY reference from the top left of the screen (Monitor).

altkey / ctrlkey : If you keep any of these keys pressed while performing your right click operation, then you can see these values are true. Otherwise, they’re false as in our case.

target: It corresponds to the element you performed the action upon. Whatever element you might have clicked on, you can see the information corresponding to this property in the console

What is a document object ?

The document consists of what is inside the inner window. The document object is the root of every node in the DOM. If you are loading an HTML page in the browser, then the document represents that entire page.

The Event.preventDefault() method and its usage

Sometime we don’t want an HTML element to behave in the way it is supposed to behave in default. In such a case, we can use this method.

Example : Clicking the anchor element will make the browser redirect to that page by default. Let’s try to avoid that.

You can create an HTML file and check out this code.

The Event.stopPropagation() method

Events flow outwards. There are certain cases, such as when you have nested elements and you perform some event on a child and it ends up performing some action on the parent, too, that you want to avoid. In such cases, this method is a useful one.

It sounds bit confusing, but I hope the below example will make it clear to you.

Imagine you have a button inside a paragraph and you have attached a mousedown event to both of them. You want to achieve the following use cases:

  • If you right click the button, then it should show that it has been clicked and does not propagate to the parent element (that is, the paragraph).
  • If you left click on the button, then it should propagate outwards normally and fire the paragraph event listener, too.

Removing an event listener from an element

In order to remove an event listener from an element, we need to call the removeEventListener method with the event name and the function name.

Note : when anonymous functions are passed, they don’t have memory mapping. So we need to define those functions outside the callback and then reference them here in the removeEventListener callback.

If you have reached this point, you should have a decent understanding of how Event Listeners work in the JavaScript.

If, while working with your favorite library/Frameworks, you ever get stuck in the Events Handling part, then these basics should help you to resolve the issue.

Read more posts .

If this article was helpful, share it .

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

Dynamically creating JavaScript elements with event handlers

javascript assign event handler

Editor’s note: This article was last updated by Kayode Adeniyi on 19 April 2023 to include information about the different types of event handlers provided by JavaScript, and the lifecycle of a JavaScript event. For more information, learn how to create custom events for your app in JavaScript .

How To Dynamically Create JavaScript Elements With Event Handlers

In this article, we’ll look at how to dynamically create JavaScript elements and how to attach event handlers to the dynamically created JavaScript elements.

We’ll cover the following:

What are event handlers in JavaScript?

Event handlers vs. event listeners, inline event handlers, traditional event handlers, dom level 0 event handlers, the lifecycle of a javascript event.

  • Dynamically creating JavaScript Handlers and attaching event handlers

The document.createElement() method

Creating an element with javascript backtick strings, template literals, what are events in javascript.

In JavaScript, events are the actions or triggers that happen in the web browser, such as clicking on a button, scrolling down a page, or submitting a form. These events/triggers can be generated by the user or by the browser itself. After they are generated, they trigger a JavaScript code to perform a certain action in response.

Similarly, events in JavaScript are triggered by specific actions and can then trigger a response in the JavaScript code that’s listening for that particular event. The way a traffic light controls the flow of traffic at an intersection, events in JavaScript can control the behavior of code.

When an event inside the JavaScript is triggered, a piece of code is executed. That code, also known as the event handler, is usually wrapped up inside a function. The event handler is usually attached to an HTML element, and it waits for the execution of an event to happen on that element.

To understand this more clearly, let’s build on our traffic light analogy. Think of an event handler as a traffic cop at an intersection. The cop waits for certain events, such as a car running a red light, to take an action that is a response to that event, such as writing the driver a ticket.

Similarly, an event handler is “listening” for specific events to occur on an HTML element. When the action occurs, the events handler is triggered and takes action by executing the JavaScript code associated with it.

Event handlers and event listeners perform similar, but not identical, tasks. The main difference between them is how they are attached to the HTML element. Event handlers are attached as attributes to the HTML element itself, while event listeners are attached using JavaScript.

The different types of event handlers provided by JavaScript

Millions of developers are actively using JavaScript and changing its ecosystem. As such, there are different types of event handlers provided by the JavaScript:

Let’s take a look at each of the handlers above to understand what functionalities they provide.

Inline event handlers can be added directly to the HTML element using the on attribute. The main benefit of using inline event handlers is their simplicity. Some examples of inline events are:

  • onclick : This event is triggered when the HTML on which it is attached gets clicked by the user. This event handler executes the code specified in its attribute
  • onsubmit : This event handler is triggered when a form is submitted. It also executes the code specified in its attributes
  • onmouseover : This event is triggered when the user moves their mouse on the element on which it is attached

Traditional event handlers are used in web development to attach event listeners to HTML elements. As every browser supports them and they have been in use for very long, their main benefit is their compatibility and flexibility.

The main difference between traditional event handlers and inline event handlers is the way they are attached to the code. Inline event handlers are attached directly with the HTML code whereas traditional event handlers are attached with HTML through a separate JavaScript code block.

javascript assign event handler

Over 200k developers use LogRocket to create better digital experiences

javascript assign event handler

Some of the traditional event handlers are:

  • onkeydown : This event is triggered and the code is executed when the user presses the down key on their keyboard
  • onscroll : When a user scrolls through an HTML document, this event handler triggers the function
  • onload : When all the resources of the HTML page are loaded, this event is triggered

DOM level 0 event handlers refer to the traditional approach that was used during the early days of the web. During this approach, we simply used to set a property on an HTML element that usually corresponds to the name of the event we want to listen for, and then we assign a function to it that gets called after the event occurs.

Some of the DOM level 0 event handlers are the same as what we have already discussed. The only difference is the way they get attached to the HTML code is different. DOM level 0 event handlers include:

  • onload : This event is triggered when a webpage has finished loading
  • onmouseout : This event is triggered when a user moves their mouse out of an element
  • onsubmit : This event is triggered when a form is submitted

When an event is triggered, there are three phases that the event flows through the DOM (Document Object Model). These phases are the capture phase, target phase, and bubbling phase.

Capture phase

During the capture phase, the event first moves from the top of the DOM hierarchy towards the target element.

Target phase

After the event reaches the target element, it triggers the event listener attached to that element. The target phase is the phase where the event actually happens.

Bubbling phase

After the target phase, the event bubbles up from the target element towards the top of the DOM hierarchy. It’s important to note that not all events go through all three phases. Some events only have a target phase, while others may skip the capture or bubbling phase. It depends on where the event was triggered.

Dynamically creating JavaScript handlers and attaching event handlers

In JavaScript, attaching event handlers on an element that is not yet created or does not exist on the page will throw an error. As a result, the event handler code won’t work.

For example:

More great articles from LogRocket:

  • Don't miss a moment with The Replay , a curated newsletter from LogRocket
  • Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

In the example above, the btn class does not exist in our index.html page. Therefore, this will throw an error of addEventListener of null.

We can dynamically create an element in JavaScript and attach event handlers with these two methods.

The document.createElement() method allows us to create the HTML elements by their tag names, like <div> , <p> , <img> , and <h1> .

When we create an element with document.createElement , it doesn’t appear on the page immediately. It is going to be stored in the JavaScript memory until it is injected in the DOM. In this article, we are going to create a simple dog profile.

We’ll dynamically create our elements, inject it to the DOM, and also attach event handlers. Follow the link to the live CodePen demo :

Here is our index.html with no element in its body. We are going to dynamically create the element from JavaScript, inject it into the DOM, and also attach event handlers to the dynamically created elements:

In our index.js, we used document.createElement() to dynamically create a new div . Then, we added a dog class to the div we created earlier.

The classList property is used to add, remove, and toggle CSS classes on an element. Next, we created an image tag with src and alt attributes. We also created the h2 tag and added text contents in it. Then, we added a new p element with a class of info that will contain more information about the dog.

Next, we’ll dynamically create a button with a class of btn . We’ll add text saying click here to read more . If you inspect your browser, you won’t see the div with a class of dog we created because we haven’t appended it yet to the DOM.

Now, we’ve dynamically created an element. The next question is: how do we inject it to the page? To inject it into the DOM, we are going to use the .appendChild() method to append the dynamically created elements.

If you inspect your console, you will see the dynamically created elements injected in your DOM. Now we can add event handlers. To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click .

We’re saying that onclick of the button, the p tag with a class of moreInfo should display block . Here is the CSS code for styling the dog profile:

JavaScript backtick strings are also known as template literals. According to MDN , template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

We are going to dynamically create an element with JavaScript template literals, inject them to the DOM, and also attach event handlers.

Check out this live demo at CodePen . Below is the screenshot of the dog profile before triggering the event that will happen after Click to read more about me is clicked:

App Demo Before An Event Is Triggered

Below is the screenshot of the site after the event gets triggered. Notice the difference, and observe how triggering the event transforms the DOM and reveals a new dev that was previously hidden and has text inside of it:

Demo After An Event Is Triggered

Now, we are going to create the dog profile we created earlier, but with a difference in the JavaScript file. Our HTML and CSS remains the same.

In the template literals.js file, we declared newDog , and use template literals to create multiple elements in it. If you console.log(newDog) , you will see the element created like a string in the console. Or, if you console.log(typeof newDog) , it is going to return a string showing that it is not yet a DOM element.

Next, we are going to use document.createRange() to turn the string into a DOM element. Then, we call the createContextualFragment() method that leaves on the range. When you console.log myFragment , you will see a range of objects (a collection of elements, or part of HTML we can work with). Then, we append myFragment to the body of the page.

N.B., If you need to do things like add event listeners or change classes, we should put it in the DOM with a createcontextual fragment and then put it in the body or anywhere else in the page.

Next, we are selecting the button with a class of .btn where the users click to read more about the dog. If you console.log(btn) , you find out that it is in the DOM because we have injected it to the DOM through the createContextual fragment.

Adding event handlers

We added an event listener of click , and called a showMore function. In the showMore function, we selected the class moreInfo . If you check on our css you find out that the text was set to display none. So now we are saying that onclick of the button, let the display none change to display block .

Congratulations! Our dog profile is complete. All elements were created dynamically, and the event handler of onclick was added to the dynamically created elements.

In this article, we explored the concepts of events, event listeners, and dynamically creating new JavaScript elements by using document.createElement and template literals. We also conveyed the different approaches that one can take while writing an event listener. Remember that each approach has its own pros and cons.

LogRocket : Debug JavaScript errors more easily by understanding the context

Debugging code is always a tedious task. But the more you understand your errors, the easier it is to fix them.

LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to see exactly what the user did that led to an error.

LogRocket records console logs, page load times, stack traces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!

Try it for free .

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • #vanilla javascript

javascript assign event handler

Stop guessing about your digital experience with LogRocket

Recent posts:.

Using Pavex For Rust Web Development

Using Pavex for Rust web development

The Pavex Rust web framework is an exciting project that provides high performance, great usability, and speed.

javascript assign event handler

Using the ResizeObserver API in React for responsive designs

With ResizeObserver, you can build aesthetic React apps with responsive components that look and behave as you intend on any device.

javascript assign event handler

Creating JavaScript tables using Tabulator

Explore React Tabulator to create interactive JavaScript tables, easily integrating pagination, search functionality, and bulk data submission.

javascript assign event handler

How to create heatmaps in JavaScript: The Heat.js library

This tutorial will explore the application of heatmaps in JavaScript projects, focusing on how to use the Heat.js library to generate them.

javascript assign event handler

One Reply to "Dynamically creating JavaScript elements with event handlers"

Thanks for the content. He helped me a lot.

Event delegation

Capturing and bubbling allow us to implement one of the most powerful event handling patterns called event delegation .

The idea is that if we have a lot of elements handled in a similar way, then instead of assigning a handler to each of them – we put a single handler on their common ancestor.

In the handler we get event.target to see where the event actually happened and handle it.

Let’s see an example – the Ba-Gua diagram reflecting the ancient Chinese philosophy.

Here it is:

The HTML is like this:

The table has 9 cells, but there could be 99 or 9999, doesn’t matter.

Our task is to highlight a cell <td> on click.

Instead of assign an onclick handler to each <td> (can be many) – we’ll setup the “catch-all” handler on <table> element.

It will use event.target to get the clicked element and highlight it.

Such a code doesn’t care how many cells there are in the table. We can add/remove <td> dynamically at any time and the highlighting will still work.

Still, there’s a drawback.

The click may occur not on the <td> , but inside it.

In our case if we take a look inside the HTML, we can see nested tags inside <td> , like <strong> :

Naturally, if a click happens on that <strong> then it becomes the value of event.target .

In the handler table.onclick we should take such event.target and find out whether the click was inside <td> or not.

Here’s the improved code:

Explanations:

  • The method elem.closest(selector) returns the nearest ancestor that matches the selector. In our case we look for <td> on the way up from the source element.
  • If event.target is not inside any <td> , then the call returns immediately, as there’s nothing to do.
  • In case of nested tables, event.target may be a <td> , but lying outside of the current table. So we check if that’s actually our table’s <td> .
  • And, if it’s so, then highlight it.

As the result, we have a fast, efficient highlighting code, that doesn’t care about the total number of <td> in the table.

Delegation example: actions in markup

There are other uses for event delegation.

Let’s say, we want to make a menu with buttons “Save”, “Load”, “Search” and so on. And there’s an object with methods save , load , search … How to match them?

The first idea may be to assign a separate handler to each button. But there’s a more elegant solution. We can add a handler for the whole menu and data-action attributes for buttons that has the method to call:

The handler reads the attribute and executes the method. Take a look at the working example:

Please note that this.onClick is bound to this in (*) . That’s important, because otherwise this inside it would reference the DOM element ( elem ), not the Menu object, and this[action] would not be what we need.

So, what advantages does delegation give us here?

  • We don’t need to write the code to assign a handler to each button. Just make a method and put it in the markup.
  • The HTML structure is flexible, we can add/remove buttons at any time.

We could also use classes .action-save , .action-load , but an attribute data-action is better semantically. And we can use it in CSS rules too.

The “behavior” pattern

We can also use event delegation to add “behaviors” to elements declaratively , with special attributes and classes.

The pattern has two parts:

  • We add a custom attribute to an element that describes its behavior.
  • A document-wide handler tracks events, and if an event happens on an attributed element – performs the action.

Behavior: Counter

For instance, here the attribute data-counter adds a behavior: “increase value on click” to buttons:

If we click a button – its value is increased. Not buttons, but the general approach is important here.

There can be as many attributes with data-counter as we want. We can add new ones to HTML at any moment. Using the event delegation we “extended” HTML, added an attribute that describes a new behavior.

When we assign an event handler to the document object, we should always use addEventListener , not document.on<event> , because the latter will cause conflicts: new handlers overwrite old ones.

For real projects it’s normal that there are many handlers on document set by different parts of the code.

Behavior: Toggler

One more example of behavior. A click on an element with the attribute data-toggle-id will show/hide the element with the given id :

Let’s note once again what we did. Now, to add toggling functionality to an element – there’s no need to know JavaScript, just use the attribute data-toggle-id .

That may become really convenient – no need to write JavaScript for every such element. Just use the behavior. The document-level handler makes it work for any element of the page.

We can combine multiple behaviors on a single element as well.

The “behavior” pattern can be an alternative to mini-fragments of JavaScript.

Event delegation is really cool! It’s one of the most helpful patterns for DOM events.

It’s often used to add the same handling for many similar elements, but not only for that.

The algorithm:

  • Put a single handler on the container.
  • In the handler – check the source element event.target .
  • If the event happened inside an element that interests us, then handle the event.
  • Simplifies initialization and saves memory: no need to add many handlers.
  • Less code: when adding or removing elements, no need to add/remove handlers.
  • DOM modifications: we can mass add/remove elements with innerHTML and the like.

The delegation has its limitations of course:

  • First, the event must be bubbling. Some events do not bubble. Also, low-level handlers should not use event.stopPropagation() .
  • Second, the delegation may add CPU load, because the container-level handler reacts on events in any place of the container, no matter whether they interest us or not. But usually the load is negligible, so we don’t take it into account.

Hide messages with delegation

There’s a list of messages with removal buttons [x] . Make the buttons work.

P.S. Should be only one event listener on the container, use event delegation.

Open a sandbox for the task.

Open the solution in a sandbox.

Create a tree that shows/hides node children on click:

Requirements:

  • Only one event handler (use delegation)
  • A click outside the node title (on an empty space) should not do anything.

The solution has two parts.

  • Wrap every tree node title into <span> . Then we can CSS-style them on :hover and handle clicks exactly on text, because <span> width is exactly the text width (unlike without it).
  • Set a handler to the tree root node and handle clicks on that <span> titles.

Sortable table

Make the table sortable: clicks on <th> elements should sort it by corresponding column.

Each <th> has the type in the attribute, like this:

In the example above the first column has numbers, and the second one – strings. The sorting function should handle sort according to the type.

Only "string" and "number" types should be supported.

The working example:

P.S. The table can be big, with any number of rows and columns.

Tooltip behavior

Create JS-code for the tooltip behavior.

When a mouse comes over an element with data-tooltip , the tooltip should appear over it, and when it’s gone then hide.

An example of annotated HTML:

Should work like this:

In this task we assume that all elements with data-tooltip have only text inside. No nested tags (yet).

  • The distance between the element and the tooltip should be 5px .
  • The tooltip should be centered relative to the element, if possible.
  • The tooltip should not cross window edges. Normally it should be above the element, but if the element is at the page top and there’s no space for the tooltip, then below it.
  • The tooltip content is given in the data-tooltip attribute. It can be arbitrary HTML.

You’ll need two events here:

  • mouseover triggers when a pointer comes over an element.
  • mouseout triggers when a pointer leaves an element.

Please use event delegation: set up two handlers on document to track all “overs” and “outs” from elements with data-tooltip and manage tooltips from there.

After the behavior is implemented, even people unfamiliar with JavaScript can add annotated elements.

P.S. Only one tooltip may show up at a time.

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

Event Handling in JavaScript

JavaScript Course With Certification: Unlocking the Power of JavaScript

Event Handling in JavaScript is a software routine that processes actions that happen when a user interacts with the page, such as mouse movements and keystrokes. Event handlers in javascript are when an event is received by an event handler from an event producer and the processes that follow. Events are handled similarly in a browser. When the browser notices a change, it notifies an event handler (a function) that is listening to a specific event. The actions are then carried out as defined by these functions.

What are Event Handlers in JavaScript?

When an event, consider pressing a keyboard key or clicking an element, occurs on a DOM or an HTML element, we can call the specific functions based on these events. Now, how does the HTML element know when to call the mentioned JavaScript code or JavaScript function? This is taken care of by the event handlers. The properties of DOM or HTML elements are called event handlers to control how an element should respond to a given event. The concept and operation of event handlers are summarised in the figure below:

event-and-event-handlers

As shown in the above figure, when a user clicks a specific mouse button or types a specific keyword into the browser, that action activates the corresponding event handler for that HTML element. The browser then shows the end users the effects of the actions that were carried out on the webpage by the JavaScript code that was executed by the event handler.

Event handlers can be assigned directly using the equal ( = ) operator because they are attributes of HTML/DOM elements as well. The syntax is as follows:

Registering Event Handlers in Javascript

For registering handlers, there are two recommended methods. By assigning the event handler code to the target element's corresponding on event property or by adding the handler as a listener for the element using the addEventListener() method, the event handler code can be made to execute when an event is triggered. The handler will receive an object that complies with the Event interface in either scenario (or a derived interface). The main difference is that using the event listener methods, additional event handlers can be added (or removed).

Different Phases of Event Handling in JavaScript

The lifecycle of a JavaScript event contains three different phases of events:

  • Capturing Phase : In the capture phase, generally known as the trickling phase, the event "trickles down" to the element that caused the event.
  • Target Phase : It starts with the element and handler at the top level and works its way down to the element. When the event arrives at the target, the capture phase is over.
  • Bubbling Phase : The event is "bubbled" up to the DOM tree during the bubble phase. The innermost handler initially captures and handles it (the one that is closest to the element on which the event occurred). After that, it moves up (or bubbles up) to the DOM tree's higher levels, moves up to its parents, and eventually returns to its root.

They follow the same order as listed above. As shown in the diagram below:

lifecycle-of-javascript-event

In event handling, when an event reaches the element, it enters the capturing phase . Events enter the target phase when they reach the element, and they up from the element during the bubbling phase .

HTML Event Handler Attributes

The names of event handlers typically start with on; for example, onclick is the name of the event handler for the click event. Use an HTML attribute with the name of the event handler to assign an event handler to an event connected to an HTML element. For example, you may use the following to run some code when a button is clicked:

In this example, the alert box appears when the button is clicked.

The HTML characters like the ampersand ( & ), double quotes ( " ), less than ( " ), and other special characters must be escaped when using JavaScript code as the value of the onclick attribute. Otherwise, a syntax error will occur.

A function defined in a script can be called by an event handler defined in HTML. For example:

When a button is clicked in this example, the myAlert() function is called. A separate <script> element defines the function " myAlert() " which could be included in a separate JavaScript file.

When using event handlers as attributes of an HTML element, the following are some important aspects:

First, without explicitly defining the event, the event object can be accessed by the code in the event handler:

Second, the event's target element is represented by the this value inside the event handler:

Third, the element's properties can be accessed by the event handler, as shown below:

Disadvantages of Using HTML Event Handler Attributes in JavaScript

Due to the following reasons, assigning event handlers using HTML event handler attributes is not regarded as a good practice and should be avoided as much as possible in event handling:

  • The event handler code is first mixed in with the HTML code, making it more difficult to extend and maintain.
  • Timing issue , Users may start interacting with the element on the webpage, which will result in an error if the element fully loads before the JavaScript code.
  • Consider the following myAlert() function, which is defined in a separate JavaScript file:

Besides this, the myAlert() function returns an unknown value when the page has fully loaded but JavaScript has not. Users will experience an error if they press the button at this time.

Event Objects

Event handler functions accept an argument, the event object, even though we haven't used it up to this point. Additional information about the event is also included in this object. For example, we can check the event object's button property to verify which mouse button was pressed.

Various Types of Event Handlers in JavaScript

JavaScript offers a variety of event handlers that are activated in response to specific actions taken on the HTML elements. A few of the event handlers in javascript are:

Propagation

For the majority of event types, the handlers registered on nodes with the children will get children-level events. If the button within a paragraph is clicked, the paragraph's event handlers can also see that click event. If both the button and the paragraph have a handler, the handler on the button, which is more specific, will execute first.

The event is said to propagate outward, from the node where it occurred to the parent node of that node and then to the document's root. After every handlers registered on the particular node has had their chance to respond to the event, the handlers that registered on the entire window are given the chance to do so.

A handler for an event can invoke the stopPropagation method on the event object at any time to prevent successive handlers from getting the event. This may be useful in event handling in javascript if, for example, we have a button inside another clickable element, and we do not want button clicks to activate the outer click behavior of an element.

Default Actions

For the majority of event types, the JavaScript event handlers are called prior to the default behavior. If the handler does not want this normal behavior to occur, typically because it has already handled the event, it can call the event object's preventDefault method.

This allows you to implement custom keyboard shortcuts and context menus. It may also be used to interfere obnoxiously with the expected behavior of users. For example, the following link cannot be followed:

JavaScript Key Events

The key events occur each time a user interacts with the keyboard . There are three main key event types in javascript that involves keyup , keydown , and keypress .

Despite its name, "keydown" is not only triggered when a key is physically pushed. When a key is pushed and held, the event is triggered each time the key is repeated. Or sometimes, you must take extra care in this case. For instance, If we add a button to the Document Object Model when a key is pushed and delete it when the key is released. Now, if the key is held down longer you may accidentally add hundreds of buttons.

Pointer Events

Pointer events are the DOM (Document Object Model) events that are triggered for a pointing device. There are some common methods for pointing at objects on a screen such as mouse (including devices that act like mice, such as trackballs and touchpads), stylus/pen, and touchscreens. The pointer is a device that is hardware-independent and can target a specific set of screen coordinates.

Mouse Clicks

When any mouse button is pressed, a number of events are triggered. Similar to the " keydown " and " keyup ", the " mouseup " and " mousedown " events are also fired when the mouse button is pushed and released. And, these occur on the DOM nodes directly under the mouse pointer at the time the event happens.

After the event, " mouseup ", the " click " event is fired on the most specified node which contains both the button press and release. For example, if we hold down the mouse button on one paragraph, and move the pointer to another paragraph, then release the button, the event " click " will occur on the element containing both paragraphs.

Events and the Event Loop

Event handlers function similarly to other asynchronous notifications. They are scheduled to run when the event occurs but must wait for other scripts to complete before they can execute.

The event loop is the key to asynchronous programming in JavaScript. JS executes all operations on a single thread, but through the use of a few smart data structures, it gives the illusion of multithreading. Let's analyze what occurs behind the scenes (at the backend).

backend-of-event-loop

The call stack is responsible for keeping track of all operations in the execution queue. A function is popped from the stack whenever it completes.

call-stack-examples

The event queue is responsible for sending new functions for processing to the stack. It complies with the queue data structure in order to maintain the correct execution order of all operations.

The event loop facilitates this process by continuously checking whether the call stack is empty. If it is empty, the event queue is used to add new functions. If not, the current function call is then executed.

event-loop-queue

A timer is created in JavaScript to execute a task or function at a specified time. Mainly in event handling in javascript, the timer is used to delay program execution or to execute JavaScript code at regular intervals. The timer allows us to delay the execution of the code. Thus, the code does not finish executing simultaneously when an event triggers or a page loads.

Sometimes it is necessary to cancel a previously scheduled event. This is actually done by storing the value returned by setTimeout and then calling clearTimeout on the value.

Debouncing in JavaScript is a technique used to enhance the performance of web browsers. A web page may contain functionality that requires time-consuming computations. As JavaScript is a single-threaded programming language, frequent implementation of such a method could negatively impact browser performance.

Debouncing is a programming method for preventing time-consuming tasks from firing so frequently that they slow down the performance of a web page. In other words, it limits the frequency of function calls.

No matter how many times you click the debounce button, it gets executed once every 3 seconds!!

DOM Level 0 Event Handlers

Every element has properties for event handlers, like onclick . As shown in the example, we set the property to a function to assign an event handler in javascript.

In this example, the function here becomes the method of the element button . And, the this value is therefore similar to the element. therefore within the event handler, we can access the property of the element:

In the event handler, you can access the properties of the element and methods by using the this value. And set the event handler property's value to null to remove the event handler as shown below:

The DOM Level 0 event handlers are still widely used due to their simplicity and browser compatibility.

DOM Level 2 Event Handlers

DOM Level 2 Event Handlers provides two primary methods for registering and deregistering event listeners:

  • addEventListener() – this method in javascript attaches an event handler to an element without overriding the existing event handlers.
  • removeEventListener() – It is an inbuilt function that removes an event handler from an element for an attached event.

The addEventListener() Method

This method takes three arguments: an event handler function, an event name, and a Boolean value instructing the method to invoke the event handler during the bubble phase ( false ) or the capture phase ( true ). As shown below:

Multiple event handlers can be added to handle a single event, as shown below:

The removeEventListener() Method

The removeEventListener() function removes an event listener added with the addEventListener() function (). However, you must pass the same arguments passed to addEventListener(). For example:

Using an anonymous event listener will not work for the following:

Which is Better - an Inline Event or addEventListener?

Before considering which one is better let's understand the differences first.

  • addEventListener allows you to register an unlimited number of event handlers.
  • removeEventListener can be used to delete the event handlers.
  • Inline events can be overwritten.
  • The useCapture flag indicates whether an event should be processed during the bundle phase or the capture phase.

These are the major differences. To ensure that HTML tags are easily readable, it is advisable to use the javascript environment for event handling. Also, use addEventListeners if multiple functions or expressions are to be applied to an event; otherwise, use inline events.

  • Event Handling in JavaScript is a software routine that processes actions that happen when a user interacts with the page, such as mouse movements and keystrokes.
  • Events are handled similarly in a browser. When the browser notices a change, it notifies an event handler (a function) that is listening to a specific event. The actions are then carried out as defined by these functions.
  • When an event, such as clicking an element or pressing a keyboard key, occurs on an HTML or DOM element, we can invoke specific functions based on these events.
  • Event handlers can be assigned directly using the equal (=) operator because they are attributes of HTML/DOM elements as well.
  • When an event reaches the element, it enters the capturing phase. Events enter the target phase when they reach the element, they up from the element during the bubbling phase.
  • Event handler functions accept an argument, the event object, even though we haven't used it up to this point. Additional information about the event is also included in this object.
  • The event loop is the key to asynchronous programming in JavaScript. JS executes all operations on a single thread, but through the use of a few smart data structures, it gives the illusion of multithreading.
  • To ensure that HTML tags are easily readable, it is advisable to use the javascript environment for event handling. Also, use addEventListeners if multiple functions or expressions are to be applied to an event; otherwise, use inline events.

JS Tutorial

Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript html dom events.

HTML DOM allows JavaScript to react to HTML events:

Reacting to Events

A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.

To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:

Examples of HTML events:

  • When a user clicks the mouse
  • When a web page has loaded
  • When an image has been loaded
  • When the mouse moves over an element
  • When an input field is changed
  • When an HTML form is submitted
  • When a user strokes a key

In this example, the content of the <h1> element is changed when a user clicks on it:

In this example, a function is called from the event handler:

Advertisement

HTML Event Attributes

To assign events to HTML elements you can use event attributes.

Assign an onclick event to a button element:

In the example above, a function named displayDate will be executed when the button is clicked.

Assign Events Using the HTML DOM

The HTML DOM allows you to assign events to HTML elements using JavaScript:

In the example above, a function named displayDate is assigned to an HTML element with the id="myBtn" .

The function will be executed when the button is clicked.

The onload and onunload Events

The onload and onunload events are triggered when the user enters or leaves the page.

The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

The onload and onunload events can be used to deal with cookies.

The oninput Event

The oninput event is often to some action while the user input data.

Below is an example of how to use the oninput to change the content of an input field.

The onchange Event

The onchange event is often used in combination with validation of input fields.

Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the content of an input field.

The onmouseover and onmouseout Events

The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML element:

Try it Yourself »

The onmousedown, onmouseup and onclick Events

The onmousedown , onmouseup , and onclick events are all parts of a mouse-click. First when a mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered.

More Examples

onmousedown and onmouseup Change an image when a user holds down the mouse button.

onload Display an alert box when the page has finished loading.

onfocus Change the background-color of an input field when it gets focus.

Mouse Events Change the color of an element when the cursor moves over it.

HTML DOM Event Object Reference

For a list of all HTML DOM events, look at our complete HTML DOM Event Object Reference .

Test Yourself with Exercises!

Exercise 1 »    Exercise 2 »    Exercise 3 »

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Event handling in the DOM

Event handling has been part of JavaScript since the language's inception. As described in our event handler tutorial , they refer to specific, user imitated actions within the webpage, such as the moving of your mouse over a link, the clicking on a link, or submission of a form. Thanks to event handling, our scripts are more interactive and are able to perform certain actions depending on the user's.

The DOM of modern web browsers such as IE5+, NS6+, and Firefox provide expanded methods and flexibility (relative to older browsers) for capturing events. In this tutorial, we explore event handling in the DOM, and the differing support for it in IE5+ and NS6+/Firefox.

The 2 traditional ways of assigning event handlers

Let's first review (for most of us, at least) the 2 common and conventional ways of setting up an event handler- via HTML, or scripting. In both cases, a function or code is attached at the end, which is executed when the handler detects the specified event.

1) Via HTML, using attributes

We can define an event handler directly inside the relevant HTML tag, by embedding it as a attribute. A piece of JavaScript is also included to tell the browser to perform something when the event occurs. For example,

<a href="http://freewarejava.com" onMouseover="window.status='Click here for Java applets';return true" onMouseout="window.status=''">Freewarejava.com</a>

Freewarejava.com

Here the event handler (onMouseover) is directly added inside the desired element (A), along with the JavaScript to execute.

2) Via scripting

You can also assign and set up event handlers to elements using scripting, and inside your script . This allows for the event handlers to be dynamically set up, without having to mess around with the HTML codes on the page.

When setting up event handlers for an element directly inside your script, the code to execute for the events must be defined inside a function. Just look at the below, which does the same thing as above, but with the event handler defined using scripting:

Notice how we attached the two functions to execute for the two events- the function names without the parenthesis . This is called a reference call to the function. When assigning a function to an event via scripting, always use a function call. If you were to include the parenthesis of the function inside the definition, an error will be generated.

  • Tutorial Introduction
  • The DOM event flow
  • Assigning event handlers in the DOM
  • Example- creating a context menu
  • JavaScript Kit
  • Free JavaScripts
  • JavaScript tutorials
  • JavaScript Reference
  • DOM Reference
  • Developer & CSS
  • Free Java Applets
  • CSS Quick Reference
  • Developer Courses

IMAGES

  1. JavaScript Event Handler

    javascript assign event handler

  2. What is Event Handlers in JavaScript & What are different types of Event?

    javascript assign event handler

  3. How to Add an Event Handler to the Window Object in JavaScript

    javascript assign event handler

  4. JavaScript event handler functions with examples

    javascript assign event handler

  5. JavaScript Events

    javascript assign event handler

  6. What is Event Handlers in JavaScript & What are different types of Event?

    javascript assign event handler

VIDEO

  1. Javascript Event handler part-2#pythontutorial

  2. Javascript Event handler part-5|Mote event types|change value tylpes#pythontutorial

  3. 30 gündə JavaScript. DƏRS 11 (Destructuring, Spreading)

  4. React Tricks: Find the appropriate TypeScript type for an Event quickly

  5. #6

  6. 16.3 JavaScript assign Value of one field to other in SAP Adobe forms

COMMENTS

  1. Event handling (overview)

    There are two recommended approaches for registering handlers. Event handler code can be made to run when an event is triggered by assigning it to the target element's corresponding onevent property, or by registering the handler as a listener for the element using the addEventListener() method. In either case the handler will receive an object that conforms to the Event interface (or a ...

  2. Add an Event Handler

    To add an event handler to an event of an element, you use the addEventListener() method of the element object: Suppose that you have a button with the class .btn: To attach an event handler to the click event, you use the following: First, define an event handler: console .log( 'Button Clicked' ); Then, use the addEventListener() method of the ...

  3. JavaScript DOM EventListener

    The addEventListener() method attaches an event handler to an element without overwriting existing event handlers. You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.

  4. EventTarget: addEventListener() method

    This creates an options object with a getter function for the passive property; the getter sets a flag, passiveSupported, to true if it gets called. That means that if the browser checks the value of the passive property on the options object, passiveSupported will be set to true; otherwise, it will remain false.We then call addEventListener() to set up a fake event handler, specifying those ...

  5. JavaScript Events

    JavaScript lets you execute code when events are detected. HTML allows event handler attributes, with JavaScript code, to be added to HTML elements. With single quotes: <element event='some JavaScript'>. With double quotes: <element event="some JavaScript">. In the following example, an onclick attribute (with code), is added to a <button> element:

  6. JavaScript Event Handlers

    That is event handling! The "event" here is a new JS meetup. When a new meetup is posted, the website meetup.com catches this change, thereby "handling" this event. It then notifies you, thus taking an "action" on the event. In a browser, events are handled similarly. The browser detects a change, and alerts a function (event handler) that is ...

  7. Handling Events in JavaScript

    There are three ways to assign event handlers. 1) HTML event handler attributes. Event handlers typically have names that begin with on, for example, the event handler for the click event is onclick. To assign an event handler to an event associated with an HTML element, you can use an HTML attribute with the name of the event handler.

  8. How to add an event handler in JavaScript

    Adding multiple event handlers to the same element. The addEventListener() method allows you to add any number of events to the same HTML element, without overwriting existing events. // Define first handler const handler = (e) => {. console.log(`Button is clicked!`); }; // Define second handler const anotherHandler = (e) => {.

  9. What is the best way to add an event in JavaScript?

    Libraries like YUI and jQuery provide methods to add events only once the DOM is ready, which can be before window.onload. They also ensure that you can add multiple event handlers so that you can use scripts from different sources without the different event handlers overwriting each other. So your practical choices are; One.

  10. How to handle event handling in JavaScript (examples and all)

    An event object is passed as an argument (optional) to the handler which contains all the information related to the event (in our case, mousedown) on the window. Open the developer tools (Inspect Element) on this page and copy paste the following code in the console panel and hit enter. console.log(event); });

  11. Introduction to browser events

    DOM-property case matters. Assign a handler to elem.onclick, not elem.ONCLICK, because DOM properties are case-sensitive.. addEventListener. The fundamental problem of the aforementioned ways to assign handlers is that we can't assign multiple handlers to one event.. Let's say, one part of our code wants to highlight a button on click, and another one wants to show a message on the same click.

  12. Dynamically creating JavaScript elements with event handlers

    To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click. We're saying that onclick of the button, the p tag with a class of moreInfo should display block. Here is the CSS code for styling the dog profile: . dog {.

  13. HTML DOM Event Properties

    HTML DOM events allow JavaScript to register different event handlers on elements in an HTML document. Events are normally used in combination with functions, and the function will not be executed before the event occurs (such as when a user clicks a button). For a tutorial about Events, read our JavaScript Events Tutorial. HTML DOM Event ...

  14. Event delegation

    Event delegation. Capturing and bubbling allow us to implement one of the most powerful event handling patterns called event delegation. The idea is that if we have a lot of elements handled in a similar way, then instead of assigning a handler to each of them - we put a single handler on their common ancestor.

  15. Event Handling in JavaScript with Examples

    Registering Event Handlers in Javascript. For registering handlers, there are two recommended methods. By assigning the event handler code to the target element's corresponding on event property or by adding the handler as a listener for the element using the addEventListener() method, the event handler code can be made to execute when an event is triggered.

  16. JavaScript DOM Events

    Reacting to Events. A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element. To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute: onclick= JavaScript. Examples of HTML events: When a user clicks the mouse. When a web page has loaded. When an image has been loaded.

  17. javascript

    Assigning event handler like so: document.addEventListener("DOMContentLoaded", myFunction); is it required for the handler function to be defined before the assignment code? In other words if the...

  18. Event handling in the DOM

    The 2 traditional ways of assigning event handlers. Let's first review (for most of us, at least) the 2 common and conventional ways of setting up an event handler- via HTML, or scripting. In both cases, a function or code is attached at the end, which is executed when the handler detects the specified event. 1) Via HTML, using attributes

  19. Assigning functions to events in javascript

    3. You can do this: select.onchange = animateMarker; Adding the () executes the function immediately, removing them means that you're assigning the function to the event handler, so that it will be executed eventually. And to answer the last part: the function () {} that wraps animateMarker is unnecessary, it is simply an anonymous function ...

  20. javascript

    1. As mentioned in other answers, you can easily assign several eventListeners to the event. Note that the name of the function is the address of the code to execute and this address is immutable. The snippet shows what works and what doesn't. var myDiv = document.getElementById('my-div'); function foo1(e) {. console.log('foo1');