[thelist] Trouble setting onClick dynamically in IE and FireFox

sam foster potatosculptor at gmail.com
Thu Sep 14 21:50:24 CDT 2006


there is no closure in Matt's code, just an anonymous function:

> e[i].onclick = function() { alert('Hey you!'); return false;};

it would be a closure if the function refered to a variable that was
in scope when the function was defined, e.g.

function starter() {
       var e = document.getElementsByTagName("a");
       var linkCount = e.length;
       // linkCount is scoped to the starter function
       for( var i=0; i < e.length; i++ ) {
           // here we define a new function, and use a closure
           // which keeps linkCount alive even when starter is finished
           e[i].onclick = function() { alert("one link of " +
linkCount); return false;};
       }
   }


> I've slightly altered your code to make it more robust, leak-free and
> unobtrusive:

While I'm being pedantic, there's something we missed. We shouldnt be
using direct assignment for the event handler. If someone else had
assigned a handler already, we just blew it away. We *should* be using
DOM2 event assignment. For that we need a little cross-browser event
function:

function addNodeEventHandler(node, evtName, fp){
  if (node.addEventListener){
    node.addEventListener(evtName, fp, false);
  } else if(node.attachEvent) {
    node.attachEvent("on"+evtName, fp);
  } else {
    // when all else fails, we need to use direct assignment
    // though you could also use the function wrapper technique
  	node["on"+evtName] = fp;
  }
}
..which is used:
addNodeEvtHdlr(e[i], "click", function(e) {
     var evt = window.event || e;
     alert("one link of " + linkCount);
     // need some more x-browser event model normalization here
     // to cancel the default action of the link
     if(evt.preventDefault) {
         // w3c dom style
        evt.preventDefault();
    } else {
        evt.returnValue = false;
    }
} );

.. all of which should be enough to convince any sane person to use a
library that provides all this for you.

Sam



More information about the thelist mailing list