Wednesday, August 20, 2008

Registering multiple functions to an event to an html object in JavaScript

The usual common way to register a function to an event to an html object in JavaScript is as follows:



//Registering mouse down event.
document.onmousedown = mouseDown;



The problem in above implementation is if you/someone also want to call some different function(s) on same event and for same html object, then only one function will gets called (probably the function which registered last to the event). So if you want to fire all registered functions of a particular event and of a particular html object, then you have to change your approach to event registration.
To register multiple functions for an event to an html object, you can use following approach:




//Function to add mulitple events to single object.
function AddEvent(obj, eventType, functionName)
{
if (obj.addEventListener)
{
obj.addEventListener(eventType, functionName, false);
return true;
}
else if (obj.attachEvent)
{
var r = obj.attachEvent("on"+eventType, functionName);
return r;
}
else
{
return false;
}
}


//Registering 3 different functions to same event and to same html object.
AddEvent(document, 'mousedown', mouseDownFirst);
AddEvent(document, 'mousedown', mouseDownSecond);
AddEvent(document, 'mousedown', mouseDownThird);


//Functions to test above registered functions.
function mouseDownFirst (){ alert('mouseDownFirst'); }
function mouseDownSecond(){ alert('mouseDownSecond'); }
function mouseDownThird (){ alert('mouseDownThird'); }




Similary to un-register functions we can write following code :


// Remove the specified function registeration for specified event handler on obj object.

//For IE
obj.removeEventListener(eventName, functionName);
//For Non-IE
obj.detachEvent("on"+eventName, functionName);



Note: Sometime to get the effect of updated JavaScript, browser cache deletion required.

Google