Wednesday, June 29th, 2005

Using CSS selectors to apply Javascript functionality

Category: Articles, JavaScript, Usability

<p>Ben Nolan has written a nice piece called Using CSS selectors to apply Javascript functionality. He looks at Ajaxian showcases, and doesn’t always like the code that is mixed in the HTML.

He goes on to explain how to use CSS selectors to abstract this code out, giving you the other benefit of a clean graceful failback model.

For example, migrating from:

<li>
<a onclick=”this.parentNode.removeChild(this)” href=”#”>
Click me to delete me
</a>
</li>

to:

<ul id=”example”>
<li>
<a href=”/someurl”>Click me to delete me</a>
</li>
</ul>

And then use css selectors to select that <a> element and add javascript functions to it.

var myrules = {
‘#example li’ : function(el){
el.onclick = function(){
this.parentNode.removeChild(this);

}
}
};

Behaviour.register(myrules);

How important is this? Especially if frameworks are churning out the code for you?

Related Content:

Posted by Dion Almaer at 3:25 pm
6 Comments

++++-
4.2 rating from 10 votes

6 Comments »

Comments feed

It can be used to painstakingly scale a single-source site back such that it will work without a JavaScript interpreter available.

Comment by Bob Ippolito — June 29, 2005

Also worth pointing out that the “tag soup” in Flickr (one of his examples) is necessary — it’s deliberately done with lots of script tags so you don’t need to wait for onload for the page to work. IIRC it was mentioned when they first moved away from Flash (in an interview?).

Comment by random — June 29, 2005

It’s terribly important. The original version of the page should be valid, semantic xhtml. All formatting should be done in CSS. All javascript should be as unobtrusive as possible.

These are good coding practices and have been. Why are we having the standards debate again?

Comment by Austin Govella — June 30, 2005

Ah, but what’s the “original” version of the page? Probably the one in the developer’s brain: there is no reason to expect the page as delivered to be optimized for anything but user experience.

The idea of “applying” behavior to markup as another dimension of the underlying model is useful, but overloading class and id probably isn’t, especially not once the behavior in question becomes nontrivial. Behavior needs its own way to attach to the content model and yet be object-oriented.

See you at the XHTML standards meetings!

Comment by Jason Harenski — June 30, 2005

Yeah, I agree.. using id and class is probably a bad idea. I typically use namespace attributes, i.e. mynamespace:sortkey=”date”

Comment by Bob Ippolito — June 30, 2005

very good

Comment by giri — December 18, 2006

Leave a comment

You must be logged in to post a comment.