Languages
[Edit]
EN

JavaScript - remove event listener

3 points
Created by:
Vanessa-Drake
418

In this article, we would like to show you how to remove event listener using JavaScript.

Quick solution:

document.querySelector('.my-div').removeEventListener('click', myFunction);

Warning: to remove the event listener we need to have access to the event name and function that was used to add the event listener before.

 

Practical example

In this example, we add click event and later using the same function we remove it to show there is no attached click event after removeEventListener() call.

Run the below code to see there is no attached click event.

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
<body>
  <div class="my-div">Click me!</div>
  <script>

    var myDiv = document.querySelector('.my-div');

    function myFunction() {                         // example event handler
        console.log('my function text');
    }
    
    myDiv.addEventListener('click', myFunction);    // adding event handler to div element
    myDiv.removeEventListener('click', myFunction); // removing event listener from div element

  </script>
</body>
</html>

References

  1. EventTarget.removeEventListener() - Web APIs | MDN
  2. Document.querySelector() - Web APIs | MDN
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join