Monday, March 10, 2008

JavaScript - Add/Remove event handlers

You can easily bind/unbind a function to an event so that it gets called whenever the
event fires on the object.
Internet Explorer DOM (Document Object Model) provides attachEvent and detachEvent methods, while Mozilla DOM provides addEventListener and removeEventListener methods to add/remove event handlers.
You can use the following cross-browser JavaScript methods to add/remove your event handlers:

function AddEventHandler(obj, eventName, functionNotify)
{
if (obj.attachEvent)
{
obj.attachEvent('on' + eventName, functionNotify);
}
else if (obj.addEventListener)
{
obj.addEventListener(eventName, functionNotify, true);
}
else
{
obj['on' + eventName] = functionNotify;
}
}

function RemoveEventHandler(obj, eventName, functionNotify)
{
if (obj.detachEvent)
{
obj.detachEvent('on' + eventName, functionNotify);
}
else if (obj.removeEventListener)
{
obj.removeEventListener(eventName, functionNotify, true);
}
else
{
obj['on' + eventName] = null;
}
}
You can call the above methods as follows:
JavaScript
function AddKeyDownEventHandler(obj)
{
AddEventHandler(obj, 'keydown', KeyDownEventHandler);
}

function KeyDownEventHandler(evnt)
{
alert('Event key code: ' + GetEventKeyCode(evnt));
}

function GetEventKeyCode(evnt)
{
return evnt.keyCode ? evnt.keyCode : evnt.charCode ? evnt.charCode :
evnt.which ? evnt.which : void 0;
}

function BodyOnloadHandler(evnt)
{
AddKeyDownEventHandler(document.getElementById('<%=txtKeyDown.ClientID%>'));
}

ASPX:

on the body tag's onload event call the "BodyONloadHandler()" method.






No comments: