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.






JavaScript - Get DOM elements with one simple method

1. Get DOM elements with one simple method
There is a cross-browser getElementById method of the document object, which
returns a reference to the object with the specified value of the ID attribute. Prototype
JavaScript Framework (http://www.prototypejs.org) provides a convenient JavaScript
method with a short name to return DOM elements:
function $() {
var elements = new Array();
for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (typeof element == 'string') element = document.getElementById(element); if (arguments.length == 1) return element; elements.push(element); } return elements; }
One nice thing about this method is that you can pass either one argument or multiple
arguments. If one argument is passed it returns a reference to the object with the
specified ID value. Otherwise it returns an array of references to the objects with the
specified ID values. Another nice thing about this method is that it takes objects as well
as strings as arguments.
Instead of the following:
var elem = document.getElementById('TextBox1');
You can now call the $ method as follows:
var elem = $('TextBox1');
Or you can return multiple DOM elements with one simple method call:
var elemArr = $('TextBox1', 'TextBox2');


Friday, March 7, 2008