DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Add Event

05.04.2009
| 2267 views |
  • submit to reddit
        Adds an Event to a Javascript object.

Cross browser compatible

<b>Usage:</b>
addEvent( elm as Object, evtType as String, fn as Function, useCapture as Boolean );


<b>Code:</b>
function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else {
		elm['on' + evType] = fn;
	}
}
    

Comments

Snippets Manager replied on Tue, 2009/05/05 - 4:34am

The above thought is smart and doesn’t require any further addition. It’s perfect thought from my side. The Bible