Removing an Event Handler

JavaScript FAQ | Keyboard & Mouse Events FAQ  

Question: How do I remove a JavaScript event handler from a page element?

Answer: Depending on your method of adding event handlers, you can remove them in several different ways:

  • 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 your handlers previously defined by assignment, for example:
  • call detachEvent to remove handlers added using attachEvent
  • call removeEventListener for handlers added using addEventListener.

You can combine the latter two calls in a cross-browser function:

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 removeEventHandler() 
// to unregister event handlers for 'button1' and 'button2':
var b1 = document.getElementById('button1');
var b2 = document.getElementById('button2');

Try adding and removing event handlers for Button 1 and Button 2 here:
If you registered the same event handler function for the same element more than once, you may also need to remove that handler multiple times. This is browser-dependent: 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).

See also:

  • How do I add an event handler for a page element?
  • How do I prevent the browser's default action in a JavaScript event handler?
  • What is event bubbling?
  • How do I cancel event bubbling?
  • Copyright © 1999-2011,