JavaScript removeEventListener() method with examples


The JavaScript removeEventListener() method is used to remove an event listener from an element that has been previously attached with the addEventListener() method.

Following is the code for removeEventListener() method −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample{
      font-size: 18px;
      font-weight: 500;
      color:red;
   }
</style>
</head>
<body>
<h1>JavaScript removeEventListener() method</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to print a number
</h3>
<button class="Btn">Remove event Listener</button>
<h3>Click on the above button to remove the event listener of the first button</h3>
<script>
   let sampleEle = document.querySelector('.sample');
   let j=0;
   function printNum(){
      sampleEle.innerHTML += 'Number = ' + j++ + '<br>';
   }
   document.querySelector('.Btn').addEventListener('click',printNum);
   document.querySelectorAll('.Btn')[1].addEventListener('click',()=>{
      document.querySelector('.Btn').removeEventListener('click',printNum);
      sampleEle.innerHTML = 'Event listener has been removed';
   })
</script>
</body>
</html>

Output

The above code will produce the following output -

On clicking ‘CLICK HERE’ three times −

On clicking the ‘Remove event Listener’ button and clicking on the ‘CLICK HERE’ button again −

Updated on: 11-May-2020

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements