8 methods to bring your front end coding to rockstar levels
8 methods to bring your front end coding to rockstar levels
|
|
There are a lot of good front end developers out their right now. If you fancy yourself as a front end editor then you really should be looking at how you can differentiate yourself from the rest. Yes there are lots of “good” front end developers, but there are not a whole lot of excellent front end developers.
1. Improve Your Semantic Names
If you work in a team or ever revisit your code and need to update it then you should think about the quality of your class and ID names. It is not uncommon for developers to use class names like “box”, “wrapper”, or “container.” While you may think that these naming conventions or “semanitc enough” none of them describe the content that is inside them. Instead consider using HTML5 spec’s such as “content-sub”, “section”, “content-aside” or “content-sup.”
You and your team will have a much easier time sorting through code that describes the content than trying to remember the details of “box.”
Read more about semantic naming from Andy Clarke and A List Apart.
2. Improve the Organization of Your Files
I think it is reasonable safe to assume that most developers have at least started to organize their files by type (ie: a folder for images, css, javascript, etc…). You can go a step further and improve the organization even more, particularly any folder that is going to have a lot of files (such as Images in particular and CSS as a secondary.)
I find it best to create sub folders with in images and separate images based on design structure, buttons, headlines, photos, etc…
There are plenty of other folders you may want to create to keep the updating and growth of a site easy and efficient, including:
- Documents
- Client files
- Copy
- Proofs
- Staged/Development area (folder for a “clone of the site” where you can make changes and get sign off)
- Downloads
The Elements CSS Framework does a great job of organizing files based on the normal client/provider workflow.
3. Use Commenting in Your XHTML
Any time you end up developing complex layouts you are bound to use a lot of <div>s in your markup. This can be particularly confusing to go back and edit as it becomes hard to figure out which div is being closed where. You may see three </div>s all in a row.
To combat this simply add some coments at each </div> (or any other closing element if you find that it will be helpful) to let you know what element was just closed.
<div id="header" class="section">
<div id="header-logo">
<h1>HTMLiZER</h1>
</div><!--/#header-logo-->
</div><!--/#header-->
If you find it useful you can take it one step further and comment the primary area you would be editing (such as the main content area, sidebar, etc…)
4. Segment Your CSS
For small 4 – 5 page brochure sites your CSS will be pretty manageable even if you don’t spend the time and effort you should into organizing and commenting. Once you start developing web applications or large sites with a vast array of design “modules” you should make sure that you organize your CSS in way that is easy to manage.
I recommend splitting your css into logical different files for better organization, such as:
- reset.css
- main.css
- structure.css
- typography.css
- print.css
- helpers.css
This way you don’t have to sort through all of the typography styling to find the area where you defined the size of the header. Likewise if you want to adjust the headings it is pretty simple to find it through a small typography.css file rather than a huge file that has everything.
5. Create a TOC With Comments in Your CSS
Every CSS file you plan on editing and extending over time should have a table of contents at the begining and a headline seperator at every section. This will allow you to easily jump to a section using “find” rather than scrolling for that one area that had the CSS you are hoping to modify.
EX
/***********
TOC:
=1: Header
=2: Content
=3: Footer
=4: Navigation
=5: Portfolio
****************/
/* ********* =1: HEADER *********** */
#header { … }
6. Compress and Combine Your CSS files
Even though it is easier to work on a site when you segment and organize your css into several different file names, it actually causes your site to load slower. The more calls the browser has to make to the server for additional files the slower it will load.
Before deploying your css files you should combine and compress them. Compressing them removes any uncessary whitespace, comments, etc… that is unnecissary when the site is live.
There are several handy tools to do this including this online version.
7. Create your own framework (or improve on another one)
As you get more experience under your belt you will find that you use the same methods and naming conventions over and over. This is helpful for several reasons and it should be encouraged. It has lots of benefits including:
- More consistant rendering due to reusing ideal CSS techniques
- Easier editing and maintenance as you can better recall what names mean
- The start of code that can be saved and reused every time
Chances are that you end up rewriting the same type of code over and over again, simply because you don’t have it stored somewhere. Some examples may be:
- A class that floats an image left / right and gives it some margin
- The structure for an unordered list navigation
- The structure for a form
- external link, pdf and download icons
- clearfix
- png fix
- Typeography baselines and hierarchies
- etc…
Rather than reusing these bits of codes write modules into your own CSS framework (or you could imrpove on another one). This way you can streamline the development process so it takes less time and improve the consistancy of your work.
8. Develop your CSS to be modular or “object oriented”
You could assign every bit of code an unique ID or adjust the margins and padding per instance. Lots of coders do this to try and get the CSS as close to the designers comp as possible. However this is inefficient in development time and file size. Establish a set rule for differnt types of content and how they should be styled, this should include basic things such as:
- Font sizing (all normal text is 12px, featured text is 14px bold)
- Margin’s (normal margin is 10px between elements, margin between two content blocks is 40px, etc…)
- All navigation tabs will have 15px height and 13px font
- etc…
This way you don’t have to rewrite the code for every new item added to the site. Additionally it will keep the site feeling consistant and well balanced visually. If all elements and every page follows the same rhythm it will feel more unified as a whole.
Some call this object oriented css, it is worth looking into for rockstar like front end coding.
Similar Posts
- Show the user where they can go, and
- Show the user where they currently are.
- You want to offer a “stylish” low-contrast and an easy-to-read high-contrast version of your site.
- You have many low-vision readers and want to give them easy access to a customized stylesheet with a larger typeface.
- Your site is schizophrenic and you want to be able to change the look quickly.
5 Ways To Optimize Your CSS
Recently I have been working on a social networking site that was experiencing downtime due to the amount of stress its users were putting on the server. I spent a good amount of time looking for ways to improve the speed of the site, and one of this was through CSS optimization.
Structure your CSS and HTML elegantly
“CSS” Stands for Cascading Style Sheets. Notice the first word, “Cascading”? The power of this language is readily available, and it is up to you, the designer, to maximize its use. It is an interesting concept that is not too difficult to grasp. Try to find instances wherein this can be applied.
For example, the code below:
<p class="someClass">First</p>
<p class="someClass">Second</p>
<p class="someClass">Third</p>
<p class="someClass">Forth</p>
<p class="someClass">Fifth</p>
Can be rewritten this way:
<div class="someClass">
<p>First</p>
<p>Second</p>
<p>Third</p>
<p>Forth</p>
<p>Fifth</p>
</div>
But what if our code looks like this:
<p class="firstClass">First</p>
<p class="someClass">Second</p>
<p class="someClass">Third</p>
<p class="someClass">Forth</p>
<p class="someClass">Fifth</p>
We can take advantage of CSS by rewriting HTML this way:
<div class="someClass">
<p class="firstClass">First</p>
<p>Second</p>
<p>Third</p>
<p>Forth</p>
<p>Fifth</p>
</div>
Then, cascade rules defined in “firstClass” to overwrite styling principles in “someClass”.
This is just one simple example, and I hope you understand what I’m trying to get at. Just keep in mind the concept of cascading rules and it won’t be long before things like this become second nature and automatic.
Re-structure your CSS
I am a huge fan of single line CSS style. Not only does it save up space, it is also more readable. The readability bit is debatable, though. Simply put, I find it easier to locate relevant tags if the tag names are all on the same left-hand side and I do not have to scroll so much to find what I need to change. After all, designers are only concerned with CSS selectors, not the rules that are applied to it.
Optimize Your CSS
Some time ago, I wrote an article about improving website performance using CSS optimizers. I still use CSS Optimiser up to this day. For very large CSS files it is a quick and easy way to rewrite things that may otherwise prove too time-consuming to optimize manuallyt.
Use CSS Shorthand Rules
When I was still learning CSS, I found shorthand rules to be quite daunting and confusing at times. But I strived to learn the shorthand syntax for every rule simply because I am lazy and do not want to bother typing the same thing over and over not to mention having to memorize all the rule names.
Compare the example longhand its equivalent shorthand below.
Original longhand:
#someid {
background-attachment: fixed;
background-color: #000000;
background-image: url(images/image.png);
background-repeat: no-repeat;
background-position: left bottom;
}
Shorthand version:
#someid { background: #000 url(images/image.png) no-repeat fixed left bottom; }
The folks over at SitePoint has a good introduction to the art of CSS Shorthand that I can recommend to anyone who’s willing to learn.
Server-side Compression
Server-side compression techniques have long been put to use by large scale applications for two main reasons. First, bandwidth is precious and expensive. Second, it does not require having to modify code for it to work. What it does require, however, is supported server software (or hardware). Hence the term “server-side”.
One such solution can easily be deployed on Apache servers. Once again SitePoint has written an introduction to server-side compression using Apache and mod_gzip.
The drawback to this is increased CPU load. Indeed, server-side compression is a double-edged sword, but usually the pros far outweigh the cons.
Using JavaScript to Style Active Navigation Elements

I’m all about efficiency when I’m writing web code. Any time I find myself writing the same functionality more than once or twice, I try to consider whether my repeated code could be wrapped into a function of some sort.
Navigation is often one of those areas where I try to improve my efficiency. I like my navigation elements to pull double duty. I want them to:
In other words, I want some sort of visual indication in my navigation that shows my user which section of my site they’re in. You can see this on the CSS Newbie site: if you click on the TOC (Table of Contents) link in the bar at the top of the page, you’ll see that link gets special styling when the table of content loads.
Now, I could manually set this on every page using a CSS class. But that’s inefficient — depending on the size of my site, I could end up writing dozens or hundreds of lines of one-off code. And why go to all that work, when you could just wrap it all up into a nice JavaScript function?
First, I’ll explain the logic behind my functions — because they won’t work equally well for every site. Then I’ll walk you through a few examples of the code that makes it all happen.
The Logic
All of my functions assume a very clean, straightforward directory structure. For example, if you have an About section, a Blog section, and a Contact section on your site, a logical directory structure might be:
/ /about/ /blog/ /contact/
And if you had several blog entries inside your blog directory, your structure might grow like this:
/ /about/ /blog/ /blog/post-one/ /blog/post-two/ /blog/post-three/ /contact/
And therefore, a function could logically assume that anything inside the blog directory should be considered a part of the blog section of your site, and mark the blog link as active for those pages. This makes our job a lot easier. And luckily, most CMS platforms make this sort of directory structure pretty easy to create.
The functions also assume that you have either a fairly shallow directory structure, or that you’re not linking to too many similarly nested directories. What I mean by this is, if you have this sort of a structure:
/ /contact/ /contact/me/ /contact/me/here/
And you wanted to link to both /contact/ and /contact/me/here/ in your navigation bar, you might run into problems distinguishing between the two. There are ways to increase precision, but they come at the cost of flexibility.
But enough of that. Let’s get to the good stuff!
A JavaScript Solution
I’ve written about this method before, when I previously talked about building intelligent navigation bars. This technique is nice because it doesn’t rely on any JS frameworks, so you can add it to older sites without needing jQuery or the like. The basic function looks like this:
function setActive() {
aObj = document.getElementById('nav').getElementsByTagName('a');
for(i=0;i<aObj.length;i++) {
if(document.location.href.indexOf(aObj[i].href)>=0) {
aObj[i].className='active';
}
}
}
This function looks for an element with an id of “nav” (presumably your navigation bar), then looks at each of the anchor tags inside it. It then compares the anchor tag’s href tag with the page’s URL. If the href tag is contained within the URL anywhere, it gives that link a class of “active,” which I can then style specially in my CSS.
As an example of what I mean by all that, if I had an anchor tag in my navigation bar that linked to “/blog/” and the page I was on was “/blog/this-is-a-post.html”, my blog link would be styled as active, because “/blog/” is contained within “/blog/this-is-a-post.html”.
As a final note, you wouldn’t want to call this function until the page was finished loading: if you call it too soon, your links won’t exist yet! So you can either call it at the very end of your document, or dynamically call it when your page is done loading, with something like this:
window.onload = setActive;
A jQuery Solution
If you are already loading a framework like jQuery (like I do on almost every site I work on these days), this sort of functionality could be written even more succinctly. And like I said earlier, I’m a sucker for efficiency. Here’s a jQuery solution that does essentially the same thing in a much smaller space:
$(document).ready(function() {
$('#nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
});
This function is making use of both native JavaScript and jQuery tricks to reach a whole new level of brevity. First, the whole thing is wrapped in a “document ready” function, which means it won’t fire until the page is loaded and our links are in place. Next, we’re looking for anchor tags inside our “nav” ID. And really, we’re looking for a very specific anchor tag: one whose href starts with (^=) a slash, followed by a part of our page’s location (location.pathname). Specifically, we’re looking for the first directory in our page’s URL.
We’re doing this by making use of the JavaScript split() method, which lets us take any string (for example, “/blog/this-is-a-post.html”) and break it into an array based on a substring (in our case, the forward slash). If you’re familiar with PHP, it’s similar to the explode() function. In our example, we’d end up with a three-part array that looked like this:
["","blog","this-is-a-post.html"]
Which means that if we look at the second value of our array (arrays start counting at zero, so [1] is the second value), that should give our first-level directory (”blog”, in our example). This lets us match any subsequent child directories with our parent in the navigation bar.
Tweaking for Home Links
Our jQuery function works great in most scenarios, but it fails if you have a “home” link where you’re just pointing to the root directory, like this:
<a href="/">Home</a>
And because I tend to have a link like that, I needed a workaround. Here’s a way to get around that with just a little more code to account for our special case:
$(document).ready(function() {
if(location.pathname != "/") {
$('#nav a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
} else $('#nav a:eq(0)').addClass('active');
});
Here, we’re checking to see if we’re in the root directory. If so, we’re skipping the loop through our anchor tags and just making a specific anchor tag active. In this case, I’m giving the active class to the first anchor in our list (which is the most common location for a home link).
And that’s that. If you know of even more efficient or fool-proof ways to accomplish this task, I’d love to hear about them in the comments section. Or if you’re skilled in a framework other than jQuery, feel free to share the equivalent code!
Note: I apologize for the long gap between articles. I had some problems while rebuilding my PC (DOA motherboard) and was without my computer for several weeks.
Use Google Code to Speed Up Development
Web development has gotten more complicated.
You’ve got to worry about a plethora of new issues that you’ve never thought about when you started doing this business: data asset management (DAM), you’ve got to build and code websites in no time fast, competition is fierce & everybody has their own web development company, you’ve got to keep your costs to a minimal, etc.
We’re here to give you one of those ideas that’ll do all of those things all at once. It’s pretty easy to do. It took me forever but i’ve finally discovered how to use SVN via TortoiseSVN (TortoiseSVN seems to be the easiest way to do SVN. Update, commit, merge files are easily executed with 2-3 clicks). If you do not have the pleasure of owning a windows machine there are many other SVN alternatives for MAC. Such a syncrosvn and versions.
What’s TortoiseSVN?
TortoiseSVN is just a open source program that manages file versions. At 3 Point 7 Designs, we discussed some methods to collaborate and keep our files updated so redundancy didn’t happen. At much of my discovery, we discovered that we can use this to also host some of our template files that we use to speed up development.
We decided that we’d host and feature our companies css/xhtml boilerplate to foster collaboration and version tracking on Google Code (code.google.com). In addition to this beautiful solution, it allows google to host our redundant files that we use for every project. Google hosting has got to be the best hosting on the internet. You can’t beat anything faster than google; they practically run and own the internet.
We just link the files to the google code repository and voila we are up and running.
Featuring 3.7 Designs Boilerplate!
We’re big fans of css frameworks. CSS frameworks are great providing quality control. It provides us the ability to get our job done quickly, efficiently and more consistently.
The 3.7 Design Boilerplate contains the file structure and the files needed to quickly start coding. It might take a while to get a hang of our id/class usages. Nonethless, it’s pretty KISS and makes sense.
Folders Structure
The following are some folders and they’re pretty self explanatory
/css – CSS files
/images – Images
/js – Javascript Files
/clientfiles – PSD, .ai, etc files go here
/concepts – concepts – currently and eventually will be moved to client files
/copy – contains word documents or text for the content of the website
CSS Files Explained
Reset.css – Some things that we commonly practice is resetting stylesheets so that they’re all at a beginning point. This is something that Eric Meyer’s blogged about.
Grid.css - We’ve added a set of grids that you can use. It’s actually a gride from 960.gs. You’re welcome to switch out any grid stylesheet here.
helper.css – This file gives you a running start if you’re prototyping a page. You can quickly using classes move block elements around with margins or padding. An example class : “ml-5” adds 5px of padding to the left side. “mh-10″ adds left and right padding. “padr-5” provides 5 px of padding on the right side, etc.
This file also contains the very important class: clearfix. If you’re not familiar with it it just primarily solves the problems of container div’s that don’t totally addup the total height of all of the child containers.
main.css This file allows is to create a base file from the reset to provide some type of consistency and legibility to the type. Often after type is reset the type is too small to read.
style.css This last file you’ll have to use locally because it’ll be key and important in customizing your website. All the other files you can link from the google code repository. This file is the file that will contain your site specific and context specific css code.
Download Boilerplate: Latest 2.0.zip
Put it all together
With all these things put together we are providing you with a starting point. If you don’t like the way we do things; that’s totally understandable. We’re hoping to inspire others to create their own or contribute to our project.
The best part of hosting your css files is that once you add more or append to your files it’ll effect all the websites that might be linking to your files.
Hope this has been most helpful.
WordPress 2.7 Released, Initial Impressions
For those who haven’t noticed, wordpress 2.7 has officially been released. While I have played around with the release candidates I am always eager to see the full release of new software, so I have already installed the update onto this site to get some initial impressions.
Obviously this is a big interface change from previous versions, and while many have hailed wordpress for having a simple and easy to use interface I never have fully agreed. Sure it is easier than some of the other CMS and blogging platforms out there, but it always had a lot to be desired in my opinion.
The Dashboard
The reorganization of the dashboard improves it’s functionality ten fold. With a quick post bar, easily to scan stats about your blog, and the news no longer takes up 75% of the page. Where previously I would instantly skip over the information on the dashboard as it was not easy to gain value or I had to hunt for what I was looking for— I now find myself glancing at the little bits before making my next action.

The New Menu
Despite some nice aesthetic improvements, the primary change that has improved the user experience is the navigation. Some of their initial menu and design decisions make sense considering the platform was originally built to be a blogging platform, and has evolved into what it is today (more of a framework). The new version really is an evolution of the platform itself to better fit the flexibility that it has adopted.

Better Labeling
While the previous versions of wordpress had fairly good labeling, the labeling of navigational elements has improved significantly. What was “Design” is now “Appearance,” and “Manage” has been forgone for a simple “Edit.”
Much Better Organization
The organization of the navigational structure has been improved leaps and bounds. Now that wordpress is used as a CMS more often pages and posts have been separated, which should make clients lives a lot easier. Both categories have logical sub categories of edit, add new, categories, etc. Media has been separated into it’s own section, no longer do you have to hunt for it in the ambiguous “manage” tab.

The administration navigation has been vastly improved, now in an area you can actually spot it seems much easier to use. A nice touch is the addition of the “tools” section, which will serve as an excellent spot for plug in settings and controls. Previously it seemed authors stuck plug in controls in any section, where this will be a bit more convenient and logical.
The New Editing Interface

The editing interface of both posts and pages has been vastly improved. Again this looks as if the changes were made to improve the capability of WordPress as a CMS. Previous versions of wordpress had what I called “option soup.” Where boxes of all sorts of options simply appeared… well… everywhere. Sure with plug ins you could turn off a lot of the options that didn’t seem to matter, but it was a hassle and certainly didn’t make wordpress easier on clients that were not tech savy.
The layout and labeling of the editor interface is much more intuitive. The more complicated items such as custom fields are located below the fold where most users can safely ignore them, and logical workflow boxes are placed where they should. For example excerpt is under the post, where tags and categories are to the right.
On the pages editor you have a handy “Page Attribute” section that allows you to select the page parent, template, and order.
Additionally in both editors you have easy options to turn on / off any section that seems unnecessary.
The Bad
The only area I have had significant trouble with is the image uploading interface. When I used the flash loader I seemed to be able to select files but not upload them, weird? Inserting the image into the post was a bit hidden, having to “show the image” and see the details in order to find the insert image is a bit clunky. Let’s face it, being able to put pictures into a site/blog is extremely important to most clients. This being as difficult as it was is not insignificant.
Overall…
Overall the upgrade is a huge improvement, especially looking from a clients perspective. The main areas I would love to see improvement is some ability to create custom write panels with out doing hacking, and easier linking interface (if you want to link to another page on your site you have to copy and paste it? come on now!) and better navigation control capabilities.
I am sure that in future releases these will be improved and wordpress will continue to excel as a framework.
Implementing CSS
CSS class examples … The selector for a CSS class is a name you choose with a period in front of it. CSS class names may not contain spaces or underscores. …Build Custom Frameworks Easily with CSS Classes
Generally speaking, I consider full-fledged CSS frameworks to be overkill on all but the most absolutely complex projects or, on the other end of the spectrum, rapid proof-of-concept prototyping. Most people only use a few of the classes that any one CSS framework provides, but then still require their users to download the entire, and largely unused, stylesheet.
However, I still think that the foundation on which CSS frameworks are built — the concept of using classes to simplify layout and standardize design across similar elements — is very much worth investigation. But instead of relying on a one-size-fits-all (snuggie-esque?) solution, I’d encourage you to take a few minutes and build a custom, simplified framework that does exactly what you need it to do.
The Back Story
I recently built a website based on a fairly regular, consistent grid. The content area was 780px wide and would contain six “columns” of content with 12-pixel gutters between each of the columns, though various elements could span one or more of those columns.

Because of the general flexibility of the content combined with the rigidity of the columnar structure, my mind immediately jumped to frameworks as a way to get this design pushed out in a hurry. But in the end, I just couldn’t justify all that overhead, even to create a flexible six-column design. So instead, I decided to write my own mini-framework to do only what I needed.
The Custom Framework
Here’s the basic CSS I ended up writing:
.col {
float: left; }
.gutter {
margin-right: 12px; }
.span1 {
width: 120px; }
.span2 {
width: 252px; }
.span3 {
width: 384px; }
.span4 {
width: 516px; }
.span5 {
width: 648px; }
.span6 {
width: 780px; }
.clear {
clear: left; }
Pretty simple stuff, right? All it contains is nine classes that I can arbitrarily assign to my structural divs to determine how the page will lay out. The first class, “col”, gets assigned to any div I want to behave like a column.
Then each column is given one of the “span” classes (using the benefit of multiple CSS classes to great effect) to determine its width — or as I thought of it at the time, the number of columns the div would span… just like using “colspan” in old-school table layouts.
Next up we have the “gutter” class, which I add to any column that should have a gutter along its right edge (which would be true for all columns except those along the very right edge of my content area). And finally, there’s a “clear” class, just to ensure that my divs behave themselves even if I didn’t entirely fill up the previous “row” of divs.
The XHTML Structure
There’s not much to the XHMTL structure for my custom framework. Essentially, it’s a bunch of divs given two or more of my nine classes to determine its behavior. For example, to create the 4-2/2-1-3 structure I highlighted in the image above, this would be the structure:
<div class="col span4 gutter">Four columns</div> <div class="col span2">Two columns here</div> <div class="col span2 gutter">Two cols and a gutter</div> <div class="col span1 gutter">Only 120px!</div> <div class="col span3">Three columns.</div>
If you’d like to see this sort of custom framework in action, it’s running on the website for the Woodsmith Shop TV show.
One Size Doesn’t Fit All
Now, I’m not saying my framework is the end-all CSS framework and that you should just copy it wholesale into your own project and expect it to work perfectly. The idea here is to take this concept and come up with a custom framework that works perfectly for your needs.
The real take-away lesson here is that for most projects, you don’t need dozens of classes and hundreds of lines of CSS just to create a flexible grid structure. I created mine with just nine CSS classes and it was sufficient to power my six-column grid. I’d be interested to see what other people (namely, you) have come up with along these same lines. Share a link in the comments!
A Simple jQuery Stylesheet Switcher
There are lots of reasons you might want to offer your users more than one CSS file for your website:
Whatever the reason, it’s amazingly easy to create a function that swaps between multiple stylesheets using jQuery.
The first step of course is to build several different CSS files, which we’ll then swap between. Once that is done, we can dive into the XHTML and jQuery that makes the magic happen.
The XHTML
First, we need to create a set of links that will allow the user to swap between CSS files. You can make this as simple or as fancy as you’d like. For the sake of brevity, my links are simple:
<ul id="nav"> <li><a href="#" rel="/path/to/style1.css">Default CSS</a></li> <li><a href="#" rel="/path/to/style2.css">Larger Text</a></li> <li><a href="#" rel="/path/to/style3.css">Something Different</a></li> </ul>
Here I have three links, each with a “rel” attribute indicating which CSS file the link will load. Technically, I could have just as easily put this information in the “href” attribute, but I didn’t want to for one specific reason: if the user has JavaScript disabled and the CSS file is listed in the href, then clicking the link will send the user to the CSS file directly (not loading it like we intended). But our way, if JS is disabled, the user gets nothing at all: which is certainly preferable to the less savory alternative.
The jQuery
Like I promised, the jQuery is really simple:
$(document).ready(function() {
$("#nav li a").click(function() {
$("link").attr("href",$(this).attr('rel'));
return false;
});
});
This function waits until the document is loaded (generally an important step when interacting with the DOM), then attaches a click function to each of our nav anchors. The function basically says, “when someone clicks on this link, replace the link (stylesheet) tag’s href attribute with the contents of this link’s rel attribute.” The “return false” at the end just stops the browser from trying to follow the link.
Of course, you might have to get more detailed if you have more than one link tag, for example, but that’s easily done by giving the link tag a class (”changeme,” for argument’s sake), and writing something like this:
$("link.changeme").attr("href",$(this).attr('rel'));
And while this stylesheet switcher is already complete, we might want to give it some memory: after all, your users might get annoyed if they have to switch their styles back to their preferences every time they visit your site. For that, we’ll need to set a cookie. And to make that easier, I’ll use the jQuery cookie plugin (which I’ve talked about previously when building a popout ad).
With the plugin loaded, we can modify our jQuery thusly:
$(document).ready(function() {
if($.cookie("css")) {
$("link").attr("href",$.cookie("css"));
}
$("#nav li a").click(function() {
$("link").attr("href",$(this).attr('rel'));
$.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
return false;
});
});
Now we have two statements. The first one checks as soon as the page is done loading to see if a cookie called “css” has been set. If so, it sets the stylesheet to be the one indicated in that cookie. Otherwise, it does nothing.
Our click function is much the same, except after we set the stylesheet, we also set a cookie. This cookie doesn’t expire for an entire year (and each time the user changes their stylesheet preferences, it would reset this timer), giving them a good 365 of CSS bliss.
Fine Tuning
There is one minor annoyance with this stylesheet switcher: there’s generally a flash of the “default” CSS when the user loads the page. That’s because the script waits until the document is “ready” before switching the link’s href. There is a way around this: moving the first “if” statement outside of the document ready function, like so:
if($.cookie("css")) {
$("link").attr("href",$.cookie("css"));
}
$(document).ready(function() {
$("#nav li a").click(function() {
$("link").attr("href",$(this).attr('rel'));
$.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
return false;
});
});
Generally speaking, you don’t want to run any jQuery until your document is ready. However, so long as your jQuery comes after your link tag in your document structure, like shown below, this shouldn’t be a major concern:
<link rel="stylesheet" type="text/css" href="style1.css" /> <script type="text/javascript" language="javascript" src="jquery.js"></script> <script type="text/javascript" language="javascript" src="jquery.cookie.js"></script> <script>... your jQuery goes here...</script>
This means your jQuery will run before the document is done loading, and thus your link tag’s href will be swapped before your CSS has been applied. As I said before, it’s generally a bad idea to manipulate the DOM before document ready, but because we know the exact tag we want to manipulate and can place our jQuery below it in the DOM, we should be safe in this one specific instance.
Here’s an example if you would like to see this technique in action.

