internet explorer - Should i assign JavaScript events directly just to unify code? -


am programming poorly or bending backwards ie assigne event handlers like:

element.someevent = somefunction;  

instead of:

element.attacheventlistener("someevent", somefunction, false); 
  • what cons , pros idea?
  • what missing out or setting self not testing , choosing proper method?

if use element.onclick = xxx; style, you're limiting (and other scripts you're using on page) single event handler event on element (any previous handler event gets bludgeoned). addeventlistener / attachevent mechanism, can attach , remove event handlers independently of 1 another, without cross-talk.

so instance, if do:

 document.getelementbyid('foo').onclick = function() {  }; 

...then previous click handler on element foo gets blown away , no longer called when foo clicked. in contrast:

 document.getelementbyid('foo').addeventlistener('click', function() {  }); 

now click handler gets called, other click handlers have been attached element also called. you're playing nicely others. :-)

it's easy create function irons these things out you:

function hookevent(element, eventname, handler) {     if (element.attachevent) {         element.attachevent("on" + eventname, handler);     }     else if (element.addeventlistener) {         element.addeventlistener(eventname, handler, false);     }     else {         element["on" + eventname] = handler;     } } 

...or if really want go town:

var hookevent = (function() {      function hookviaattach(element, eventname, handler) {         element.attachevent("on" + eventname, handler);     }     function hookviaadd(element, eventname, handler) {         element.addeventlistener(eventname, handler, false);     }     function hookdom0(element, eventname, handler) {         element["on" + eventname] = handler;     }      if (document.attachevent) {         return hookviaattach;     }     if (document.addeventlistener) {         return hookviaadd;     }     return hookdom0; })(); 

...which creates function detects once kind of handler use , uses throughout.

frankly, though, stuff it's useful leverage work of others , use library jquery, prototype, yui, closure, or any of several others.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -