Unobtrusive Javascript, and CSS Selectors

Check this out!

I found this through Donncha’s blog. Here’s the explanation.

Basically, it’s unobtrusive JavaScript, using CSS selectors to apply the script, instead of class names.

The method I use myself is class names. For instance, check out Tyrone Guthrie’s website. The menu in that uses JavaScript, but I despise overuse of JavaScript, and always write as if for plain HTML, applying the script as an afterthought.

If you look at the source of that page, you will see that there is a script “/j/jsloader.js” loaded at the head of the page, and the only indication of where to apply the script is done by giving the navigation’s wrapping element a class of “magicmenuleft“. The script searches for that, then applies certain functions to elements containing that class.

The method used by Ben Nolan is similar, but even less intrusive. We both use CSS selectors, but his is possibly more efficient, bandwidth-wise.

There is a supposed problem which is that CSS classes are “supposed to be” used just for style. I don’t really think that’s the case, though. If you step back and look at it objectively, the word “class” means “group of similar items”. In this case, a class could be either a group of items that look the same, or a group of items with similar behaviour. I always choose the latter explanation when applying unobtrusive javascript using the class name method, but Ben’s method works around that, just in case there are any pedantic scripters around that are too snobby to stoop to misusing a class name 😉

Speaking of unobtrusive javascript; run a search, and you’ll see that it’s exploding at the moment. A few months ago, it was a mere blip on the radar, but it seems to be pretty popular now.

Comments are closed.

%d bloggers like this: