How to add event listener on html elements?

Asked 19-Jul-2021
Viewed 191 times

0

How to add event listener on html elements?


1 Answer


2

The addEventListener() method attaches an event handler to the specified element.
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.
The addEventListener() method makes it easier to control how the event reacts to bubbling.
When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.
You can easily remove an event listener by using the removeEventListener() method.
Syntax
element.addEventListener(event, function, useCapture);
The first parameter is the type of the event (like 'click' or 'mousedown', etc )The second parameter is the function we want to call when the event occurs.
The third parameter is a boolean value specifying whether to use event bubbling or event capturing. This parameter is optional.
<!DOCTYPE html>

<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
<button id='myBtn'>Try it</button>
<script>
document.getElementById('myBtn').addEventListener('click', function() {
  alert('Hello World!');
});
</script>
</body>
</html>

Loading...
Ads