Refinance now before rates go up! Get multiple rate quotes at GetMyLender.com.

How To Remove A JavaScript Event Listener From An HTML Element?

In this post, we are going to learn to detach or remove JavaScript event listener. If you want to know more about adding javascript event handler then please visit : How to add a JavaScript event handler to an HTML page element?

In that above link of post, we learn different types of adding event handlers. Depending on your methods of adding event handlers, you can remove them in several different ways.

Following ways are used to remove event listener from html element according to added event handler types :

- overwrite the HTML code containing inline event handlers with the code that does not have them (you can use innerHTML to do this)

- set to null to your handlers previously defined by assignment, for example: document.onkeydown=null;

As we already learn, modern browsers provide additional programmatic ways of registering event handlers for page elements, allowing you to dynamically add one or more handlers during the webpage lifecycle. For example, you can programmatically add handlerFunction as an onclick event handler for an element. According to that we can detach or remove event listener as like below :


 function removeEventHandler(elem, eventType, handler) {
  if (elem.removeEventListener)
   elem.removeEventListener (eventType, handler, false);
  if (elem.detachEvent) 
   elem.detachEvent ('on'+eventType, handler);
 }
   
 // Here is an example of calling removeEventListener() 
 // to unregister event handlers for 'btnSave' and 'btnClear':
  
 var formSave = document.getElementById('btnSave');
 var formClear = document.getElementById('btnClear');
  
 removeEventHandler(formSave, 'click', yourHandlerFunction1);
 removeEventHandler(formClear, 'click', yourHandlerFunction2);
  

Note :

These methods of detach or remove event listener are browser dependent. If you are registered the same event handler function for the same element more than once, you may also need to remove that handler multiple times.

For example, IE8 would need multiple detachEvent calls, while in Firefox 3 each handler function can be removed in just one removeEventListener call (per element).


Conclusion :

I hope that this article would have helped you in understanding to remove a JavaScript Event Listener from an HTML element. Please share your knowledge if you know more about this topic. Your feedback and constructive contributions are always welcome.


No comments:

Post a Comment