How to un bind an event from a HTML element

Sometimes we need to stop an event being fired. We can remove/unbind that particular event with the use of removeEventListener method in JavaScript.

For an example, let’s say we need to unbind the function named ‘test’ from the event ‘onkeypress’ event. Then we can use the removeEventListener method as follows,

HTML code

<input type=”text” onkeypress=”test();” id=”textboxID” />

JavaScript code

function test()
  // Some code here

function removeEvent()
  var elementObject = document.getElementById(“textboxID”);
  elementObject.removeEventListener("onkeypress", test);

Here the elementObject is the object which has the event.

No comments: