Over a million developers have joined DZone.

Add Event

DZone's Guide to

Add Event

Free Resource
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;

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}