Advanced Styling with CSS and JavaScript

By Alex McKee

Due to the deficiencies of one particular browser, developers today have an ugly choice: to clutter up their markup with otherwise unnecessary classes, or to serve a less styled document to Internet Explorer. In many cases, the former is the only option due to the clients expectation that a website should work identically in all browsers (despite industry professionals having long favoured graceful degradation).

This tutorial is an attempt to provide the long suffering developer with a third option – scripted styling.

JavaScript

Users of the web today fall broadly into two camps:

Power user
Uses an A grade browser, such as Mozilla Firefox, Opera or Safari
Has a good understanding of the web and how it works
Might possibly have scripting disabled
Is an industry professional or a ‘prosumer’
Might possibly be using IE although aware of shortcomings
The reluctant user
Almost guaranteed to be using IE6 or possibly IE7
Does not understand how the web works, believes that if a web page does not behave as 99% of the other pages do then it is ‘broken’.
Will not have scripting turned off, configuration is ‘computer wizardry’

Because we can rely on a sizable number of the latter visiting our site, we do need to accomodate them. Due to client expectations, the site must work similarly in all browsers.

As mentioned above, this usually means making sacrifices to your clean and tidy mark-up and liberally using classes, often on deeply nested elements – a maintenance nightmare.

However, one thing is obvious – JavaScript is usually well enough supported by all users to allow it as a tool, a powerful one at that. Those users who might disable JS will usually be using a browser that supports the CSS anway. With a little scripting, we can programatically assign classes to elements, allowing us to reliably style using more advanced selectors – cutting out the need for so many classes.

We will be using mootools although these methods can be easily adapted for use with most libraries.

For simplicity, I advise you to grab a copy of mootools to follow the tutorial with.

Example: Select by attribute

In a previous tutorial, open links in a new window, we left off with a visual indicator that only worked in modern (or dare I say it, proper) browsers, not in IE. This was because we used an attribute selector to select links with a rel attribute set to external.

CSS:

a[rel=external] { background: url(external.gif) no-repeat right center; padding-right: 1em; } a.external { background: url(external.gif) no-repeat right center; padding-right: 1em; }