
178 views
JavaScript addEventListener()
The addEventListener()
method in JavaScript is used to attach an event listener to an element. It allows you to specify a function or code that should be executed when a specific event occurs on the element.
The syntax for using addEventListener()
is as follows:
JavaScript
element.addEventListener(event, function, useCapture);
element
is the DOM element to which you want to attach the event listener.event
is a string representing the name of the event you want to listen for (e.g., “click”, “mouseover”, “keydown”).function
is the function or code that should be executed when the specified event occurs.useCapture
(optional) is a boolean value that specifies whether the event should be handled in the capturing phase (true
) or the bubbling phase (false
). It is typically set tofalse
(bubbling phase) if not specified.
Here’s an example that demonstrates how to use addEventListener()
:
HTML<span role="button" tabindex="0" data-code="<button id="myButton">Click me
<button id="myButton">Click me</button>
JavaScript
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
// Code to be executed when the button is clicked
console.log("Button clicked!");
});
In this example, the addEventListener()
method is used to attach a click event listener to the button element. When the button is clicked, the provided function is executed, which logs a message to the console.
You can attach multiple event listeners to the same element for different events, and you can also remove event listeners using the removeEventListener()
method when they are no longer needed.