HTML - DOM Element addEventListener() Method



The HTML DOM Element addEventListener() method is used to attach an event handler (listener) to specified elements such as buttons, inputs, selects, divs, etc. The event handler refers to built-in events available in JavaScript, which are triggered on user interactions.

This allows the elements to respond to user actions such as clicks, mouseover, change, focus, key press, etc.

Syntax

Following is the syntax of the HTML DOM Element addEventListener() method −

 element.addEventListener(event, function, useCapture) 

Parameters

This method accepts three parameters as listed below −

Parameter Description
event Specifies the type of event to listen for, like click, mouseover, keypress, etc.
function Defines the function to be executed when the specified event occurs.
useCapture (Optional) Determines the event handling phase:
- If true, the event handler is executed during the capturing phase.
- If false (default), the event handler is executed during the bubbling phase.

Return Value

This method does not return a value; instead, it attaches event listeners to elements.

Example 1: Adding "Click" Event Listener

The following is the basic example of the HTML DOM Element addEventListener() method. It adds a "click" event to a <button> element −

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM Element addEventListener</title>
</head>
<body>
<h3>HTML - DOM Element addEventListener() Method</h3>
<p>Click below button to add "click" event.</p>
<button id="myButton">Add click event</button>
<script>
   var button = document.getElementById('myButton');
   button.addEventListener('click', function() {
      alert('Button clicked!');
   });
</script>
</body>
</html>

When the button clicks, a "click" event will be added to it, and a message will pop that says "Button" clicked!".

Example 2: "MouseOver" Event on Div

Following is another example of theaddEventListener()method. We use this method to add a "mouseover" event on the <div> element −

<!DOCTYPE html>
<html>
<head>
<title>Mouse Over Event Example</title>
<style>
   .myDiv {
       width: 200px;
       height: 200px;
       background-color: lightgray;
   }
</style>
</head>
<body>
<h3>HTML DOM Element addEventListener() Method</h3>
<p>Mouse Over Event</p>
<div class="myDiv" id="myDiv">Hover over me!</div>
<script>
   var div = document.getElementById('myDiv');     
   div.addEventListener('mouseover', function() {
      div.style.backgroundColor = 'lightblue';
   });
   div.addEventListener('mouseout', function() {
      div.style.backgroundColor = 'lightgray';
   });
</script>
</body>
</html>

When the user mouse over the displayed box, the background will change to "light blue".

Example 3: "KeyPress" Event Listener

In the example below, we use the addEventListener() method to add a "keypress" event to the <body> element when the keyboard key is pressed −

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM Element addEventListener</title>
</head>
<body>
<h3>HTML DOM Element addEventListener() Method</h3>
<p>Key Press Event</p>
<p>Press any key.....</p>
<script>
   document.body.addEventListener('keypress', function(event) {
      alert('You pressed the key: ' + event.key);
   });
</script>
</body>
</html>

When any key on the keyboard is pressed, a message will be displayed saying the key-name, which you pressed. However, it will not reflect for non-printable keys.

Example 4: Adding "Submit" Event Listener

This example attaches a "submit" event to a form using the addEventListener() method and used event.preventDefault() method to prevent default form submission behavior −

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM Element addEventListener</title>
</head>
<body>
<h3>HTML DOM Element addEventListener() Method</h3>
<p>Submit Form Event</p>
<form id="myForm">
   <input type="text" name="username" placeholder="Enter your name">
   <button type="submit">Submit</button>
</form>
<script>
   document.getElementById('myForm').addEventListener('submit', (event)=> {
       event.preventDefault();
       var username = event.target.elements.username.value;
       alert('Hello, ' + username + '! You submitted the form!');
   });
</script>
</body>
</html>

The above program attaches a "submit" event to the form and pops up a message displaying the data you entered in the input field.

Example 5: Adding "change" Event Listener

The following attaches a "change" event to a select element using the addEventListener() method. When you try to select another option in the drop-down it will pop an alert message −

<!DOCTYPE html>
<html>
<head>
<title>HTML DOM Element addEventListener()</title>
</head>
<body>
<h3>HTML DOM Element addEventListener() Method</h3>
<p>Change Event</p>
<p>Select any Option...</p>
<select id="mySelect">
   <option value="1">Option 1</option>
   <option value="2">Option 2</option>
   <option value="3">Option 3</option>
</select>
   <script>
   document.getElementById('mySelect').addEventListener('change', (event)=> {
      alert('You selected option: ' + event.target.value);
   });
   </script>
</body>
</html>

When you select another option in the drop-down, a message will pop up showing which option you have selected.

Example 6: Adding "focus" Event Listener

This example shows how to use an event listener to respond to focus and blur events on an input field based on user interaction with the web-page −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML </title>
</head>
<body>
<h3>HTML - DOM Element addEventListener() Method</h3>
<p>Focus Event</p>
<label for="nameInput">Enter your name:</label>
<input type="text" id="nameInput">
<p id="message"></p>
<script>
   document.addEventListener('DOMContentLoaded', function() {
      let nameInput = document.getElementById('nameInput');
      let messageBox = document.getElementById('message');
      nameInput.addEventListener('focus', function() {
         messageBox.textContent = 'Input field focused.';
         messageBox.style.color = 'green';
      });
      nameInput.addEventListener('blur', function() {
         messageBox.textContent = 'Input field blurred.';
         messageBox.style.color = 'black';
      });
   });
</script>
</body>
</html>     

Supported Browsers

Method Chrome Edge Firefox Safari Opera
addEventListener() Yes 5.0 Yes 10.0 Yes 16.0 Yes 5.1 Yes 10.6
html_dom.htm
Advertisements