Archive for the ‘Javascript’ Category

CrossBrowser Event Listeners

Thursday, June 24th, 2010

DOM Level 0

var myButton = document.getElementById(“myButton”);
myButton.onclick = function(){
  alert(this.id);
};

myButton.onclick = null; //remove onclick

Internet Explorer

var myButton = document.getElementById("myButton");
myButton.attachEvent("onclick", function() {
  alert("ie click");
});

Remove Event Handler (IE)

var myButton = document.getElementById("myButton");
var myFun = function() {
  alert("hello world");
}

myButton.attachEvent("onclick", myFun);
myButton.detachEvent("onclick", myFun);

DOM Level 2

Event Listener with anonymous function:

var myButton = document.getElementById(“myButton”);
myButton.addEventListener("click", function(){
  alert(this.id);
}, false);

With DOM Level 2 multiple event handlers can be added:

var myButton = document.getElementById(“myButton”);

myButton.addEventListener("click", function()  {
alert("first event listener");
}, false);

myButton.addEventListener("click", function(){
alert("second event listener");

}, false);

Remove Event handler

var myButton = document.getElementById("myButton");
var myFun = function() {
  alert("hello world");
}

myButton.addEventListener("click", myFun, false);
myButton.removeEventListener("click", myFun, false);

CrossBrowser Event Handling (JQuery)

var addEvent = function(el. ev, fn) {
  if(el.addEventListener) {
    el.addEventListener(ev, fn, false);
  } else if(el.attachEvent) {
    el.attachEvent("on" + ev, fn);
  } else {
    el["on" + ev] = fn;
  }
}

}

Some more efficient ways for CrossBrowser Event Handling:
http://www.javascriptrules.com/2009/07/22/cross-browser-event-listener-with-design-patterns/
http://dean.edwards.name/weblog/2005/10/add-event/


Some Javascript Links – 06/09/10

Wednesday, June 9th, 2010

Inheritance Patterns in JavaScript
Inheritance Antipattern
Your JavaScript Library
Google Closure Library