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

  • submit to reddit
        Adds an Event to a Javascript object.

Cross browser compatible

addEvent( elm as Object, evtType as String, fn as Function, useCapture as Boolean );

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;


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