[thelist] unobtrusify a lot of things...

ben morrison morrison.ben at gmail.com
Thu Dec 6 10:36:27 CST 2007


On Dec 6, 2007 4:15 PM, Jon Hughes <hughesj at firemtn.com> wrote:
> Good morning, list!
>
> I have a question of best practices here -
>
> Currently, I have a function which I call unobtrusifier.
>
> Function unobtrusifier() {
>         Var emphasis =
> getElementById("navigation").getElementsByTagName("em");
>         for(var I = 0; i<emphasis.length;i++) {
>                 emphasis[i].onClick = function() { alert("hello"); }
>         }
>

> Window.onload = unobtrusifier;
>

>
> Is this how I should be doing it?  It works, but if there's a more
> semantic way (or preferred way) of doing it, I would like to know.

The preferred method is to attach events rather than use onclick, as
usual there are browser quirks with this method

attachEvent() and addEventListener() - more info here:

http://www.quirksmode.org/js/events_advanced.html

You may want to look at using a JS library such as the YUI event,
which will take care of browser inconsistencies for you

http://developer.yahoo.com/yui/event/

Once you get used to that, you should then look at using event
delegation as this is faster and extensible

http://icant.co.uk/sandbox/eventdelegation/

Also in your example

emphasis[i].onClick = function() { alert("hello"); }

it would be impossible to add in a dynamic value such as alert("hello" + i);

This is because i would always be equal to emphasis.length, this is
often referred to as closures - which i will not try to explain as
they still confuse me at times.

archived answer for closure issues:
http://lists.evolt.org/pipermail/javascript/2007-July/012274.html

ben

-- 
Ben Morrison
http://www.benjaminmorrison.com



More information about the thelist mailing list