Snippets v2

Languages
My Snippets

Event Listener Cross Browser Login or Register to Bookmark this snippet

Description Javascript

Add an Event to an element that works Cross Browser

@elm: element, can be the element onject or string ID of the element
@evtype: string event name without "on" prefix.
@fn: function reference, executed with event
@usecapture: true of false. Use false if you're unsure what this does.

The Code Download
  1. function addEvent (elm, evtype, fn, usecapture) {
  2.     //check if all required variables are defined
  3.     if (elm && evtype && fn) {
  4.         //all variables required have been supplied
  5.         if (typeof elm == "string") {
  6.             //the id was supplied, get the object reference
  7.             elm = xGetElementById(elm);
  8.         }
  9.         //add listener
  10.         if (elm.addEventListener) {
  11.             elm.addEventListener(evtype, fn, usecapture);
  12.             return true;
  13.         } else if (elm.attachEvent) {
  14.             var r = elm.attachEvent("on" + evtype, fn);
  15.             return r;
  16.         } else {
  17.             elm["on" + evtype] = fn;
  18.         }
  19.     } else {
  20.         //notify user of problem
  21.         alert('Incorrect number of parameters for addEvent function');
  22.         return false;
  23.     }
  24. }
Credits Contact JC

Added by JC on 12th November, 2007

Comments

There are no comments about this snippet.

Post Comment HTML is allowed

You must be registered and logged in to post a comment.

Login here to post a comment