tags:

views:

30

answers:

2

Say for example, we don't know how many functions already binded to an event. In that case we can bind our own function like below

var old = (element.onclick) ? element.onclick : function () {};
element.onclick = function () {old(); myOwn()};

Now how to unbind myOwn function alone without disturbing others?

A: 

you can detach the event using detachEvent - if you google this there are some functions others have written that use this method and make so IE can handle it properly too.

matpol
+1  A: 

When attaching multiple events to a DOM element, you should not change the "onfoo" attribute. Rather, use addEventListener("foo") (or attachEvent("foo") in IE). Similarly, you have removeEventListener (detatchEvent in IE) to remove events.

var myEventHandler = function (e) {
  alert("do stuff");
}

var myDomElement = document.getElementById("my_id");

myDomElement.addEventListener("click", myEventHandler, true);
myDomElement.attachEvent("click", myEventHandler); // IE

myDomElement.removeEventListener("click", myEventHandler, true);
myDomElement.detachEvent("click", myEventHandler); // IE

Replace "onfoo" with "foo". So when you do element.onmouseup, you should instead do element.addEventListener("mouseup", ...).

It is imperative that you use a function reference, since the internal object ID of the function is used for reference, and not it's contents. This will not work:

myDomElement.addEventListener("click", function () { alert("foo") }, true)
myDomElement.removeEventListener("click", function () { alert("foo") }, true)

You can create a simple wrapper for cross browser compatibility.

var addEventListener = function (element, event, func) {
  if (element.addEventListener) {
    element.addEventListener(event, func, true);
  } else {
    element.attachEvent(event, func);
  }
}
August Lilleaas