Skip to content

Instantly share code, notes, and snippets.

@ghostwriter
Created January 21, 2016 07:56
Show Gist options
  • Save ghostwriter/c156bebe04c5e8425986 to your computer and use it in GitHub Desktop.
Save ghostwriter/c156bebe04c5e8425986 to your computer and use it in GitHub Desktop.
Allows you to assign an event handler to an element.

addEvent ()

Allows you to assign an event handler to an element.

Code:

function addEvent(obj, eventName, callback){
	if (obj.addEventListener){
		obj.addEventListener(eventName, callback, false);
	} else if (obj.attachEvent){
		obj.attachEvent("on"+eventName, function(e){ return callback.call(obj, e); });
	}
}

Syntax:

void addEvent (element obj, string eventName, function callback)

Case:

obj - The target element.
eventName - The type of event to record.
callback - The function that will be executed at the outbreak of the event.

Return Values:

No value is returned.

Example with addEvent ()

addEvent(window, "load", function() {
    alert("the page has successfully loaded!");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment