Removing listener from inside outer function in JavaScript?

To remove listener from outer function, use removeEventListener().


Following is the code −

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet"
<script src=""></script>
<script src=""></script>
<button id="demo">Press Me</button>
   var demoId = document.getElementById('demo');
   demoId.addEventListener('click', function fun() {
      outerFunction(this, fun);
   }, false);
   function outerFunction(self, funct) {
      console.log('outer function is called....');
      self.removeEventListener('click', funct, false);
      console.log("Listener has been removed...")

To run the above program, save the file name anyName.html(index.html) and right click on the file. Select the option “Open with live server” in VS Code editor.


This will produce the following output −

After clicking the button “Press Me”.

This will produce the following output on console −