with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

UnObtrusive DOM: Separating HTML, CSS, and Javascript

Tuesday, June 21st, 2005

Call it the Trinity if you like. The time has come. It’s 2005, and as I’ve said before (as well as several others), It is The Year of the DOM.

But what’s different? What’s going to change? As far as Javascript is concerned, it too is an intravert. Not too long ago; or at least in the last couple of years, folks have finally come to realize that they can fully separate style from content. IE: HTML and CSS. However sitting patiently nested among (x)html lies remnants of javascript…

Why oh why must I hang out with the DOM

- Ponders Javascript.

I have all the power I need from the DOM level 0 specs. It makes no sense for me to mangle myself up in “tags” and “attributes” - so what is keeping me tied down in shackles to these simple minded (x)html documents? Oh Web developer, free my soul!


Ok, so hopefully I’ve prefaced this article well enough. By now you should all get that it’s time to fully separate your html from your css from your Javascript. Make sense? Need more clarification?

Ok, you remember the days of font tags? Right. You’re thinking

I’m way the <explicitive> ahead of ya

Ok, you remember when you use were beginning to migrate css into your documents… mainly to style text, add some background colors, maybe fancy schmancy border here or there? You’d sometimes (or a lot of times) use an inline style, or a class name that was obvious for what it was… Eg.


a.redColor { color:red; }
<a href="#" class="redColor">My red Link</a>

Well, that’s what we’re doing with javascript now! Ergo “onclick”, “onload”, “onblur”, “onMyButt”.

Not to mention throwing <script> tags in the middle of the document somewhere. Granted, there are times when we need to hack page and accessing anything “above the head” is out of the question. If that’s the case, yell at your systems architect for designing the application that way.

Unobtrusive Javascript

This is way it was always meant to be. Aside from DOM inconsistencies between different browsers and proprietary methods etc, I’m sure all browser vendors had the word “unobtrusive” stuck in their mind at one time or another.

It’s a simple philosophy really. A philosophy really similar to the judeo-christian religion. Have you heard of the trinity?

Great, the last <explicitive> thing I need is a lesson on religion

There is God. God is the document as a whole. God is also three persons, or rather, three separate beings or spirituals or…whatever. This is what we know as the entire document; the file, coded page in its entirety. Living among it, or in it, is three separate technologies.

  1. (x)HTML
  2. CSS
  3. Javascript

Together they create the Document. The technology as some of us know as “DHTML” - the ‘D’ conducively representing “Dynamic”, allows us to manipulate the HTML/CSS document. DHTML plays a large role in manipulating styles among the HTML document upon user activity.

So, back to this Unobtrusive Javascript thing, we need to separate it from the other two technologies.

As a quick example, let’s take a look at this example given to us from Stuart Langridge, (who by the way, has left a comment on my Year of the DOM article) from his new book DHTML Utopia: Modern Web Design.


function uppercaseListener() {
this.value = this.value.toUpperCase();
}
function installListeners() {
var element = document.getElementById('street');
element.addEventListener('change', uppercaseListener, false);
}
window.addEventListener('load', installListeners, false);

I figured it would be ok to use this since this is free to access via the Sitepoint Free downloadable chapters. So I should be safe.

You can see how normally this might only require a little less code. But in this fashion, the Javascript can live separately in its own cozy cuddely fury (I don’t know where I pulled fury from) file. The HTML can remain virtually untouched. No onclicks. No onloads. No onMyButts! In this case we changed the input value to transform to uppercase upon moving away from the field.

This brief example shows us how we can begin to migrate to this new philosophy.

Why is this a good philosophy

Quite frankly, there are many arguments against it. Some feel it’s nice attaching the onclick event handler to the elements to which they belong. I say boohoo…. Oh… right… you’re not convinced yet.

What happens when you want to change the functionality of a certain element. Or better yet, remove it? Now you have to access two files, remove a function, get rid of the event handler, and there are starving trees in somalia!

More reasons…

It’s philosophically correct. You need separation. This also allows for improvement on accessibility. You’ll be challenged to make your document accessible via the document itself without javascript. HTML should be able to survive on its own without the aid of Javascript (and of course, CSS).

Separating your Javascript from the rest of the document simply makes better sense. You must think of it like importing a css file. Thus in the same manner, you would import your javascript via the ’src’ attribute of the ’script’ tag.

Let this be a short lesson. And hopefully more to come on how to practice this method.

7 Responses to “UnObtrusive DOM: Separating HTML, CSS, and Javascript”

  1. Chrissy

    I like how you write. I have no idea what you are talking about, but it was funny to read. I do understand the whole 3 in 1 idea though.

  2. jordan

    Javascript is even more complex than it used to be, with this huge focus on the DOM.

    I’ve never been really been able to do anything beyond opening windows, and now it looks like I’ll never be able to figure it out.

    Guess it’s a good thing I don’t need it…

  3. Dustin

    @chrissy:
    thanks. I love you.

    @jordan:
    nobody really needs javascript. that’s where the fallacy begins. it should only be an enhancement. a usability booster, not an accessibility killer.

    by separating your html from javascript, you now no longer bind an element to a particular event.

    If for instance you had an <a> tag with an ‘onclick’ event handler, well, now you’re bound to the ‘click’ event, and click event only.

    If it were separated, you could attach as many as you like (and remove) from a distance without even touching your html.

    (Is this beginning to sound like style sheets?)

  4. Justin P.

    Great little article Dustin, glad to see you’re still alive ;)

    One should note that the method shown for attaching event listeners will not work in IE. I always use the global event attaching method by Scott Andrew.

    Keep it up!

  5. Dustin

    scott andrew’s approach is definitely the best. this was merely used as an example with DOM methods.

    For this area, this is no time to play the Mozilla elitist, and Scott does a good job of making an exception to make event attaching compatible with Internet Explorer.

  6. Justin P.

    Of course, sorry to be pedantic. I figured,j ust in case somebody decides to copy/paste your code and then says “Hey, this doesn’t even work…”, I could save them the headache :)

  7. Justin P.

    I see now, that code just came straight from the SitePoint article (guesss I shoulda followed the link), nevermind my previous comments.

Get "JavaScript Design Patterns"

"As a web developer, you'll already know that JavaScript™ is a powerful language, allowing you to add an impressive array of dynamic functionality to otherwise static web sites. But there is more power waiting to be unlocked--JavaScript is capable of full object-oriented capabilities, and by applying OOP principles, best practices, and design patterns to your code, you can make it more powerful, more efficient, and easier to work with alone or as part of a team."

Buy JS Design Patterns from Amazon.com Buy JS Design Patterns from Apress

All content copyright © 2003 - 2009 under the Creative Commons License.

Archives | Blog Search