- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
<!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 −
Advertisements
To Continue Learning Please Login
Login with Google