Wednesday, June 29th, 2005
Using CSS selectors to apply Javascript functionality
<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?








It can be used to painstakingly scale a single-source site back such that it will work without a JavaScript interpreter available.
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?).
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?
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!
Yeah, I agree.. using id and class is probably a bad idea. I typically use namespace attributes, i.e. mynamespace:sortkey=”date”
very good