24 October 2008

CSS can replace many lines of Javascript

Here's a trick that has saved me dozens of lines of javascript. Say you need to toggle your page between two modes - for example beginner/expert, verbose/concise, update/read-only, screen/printer. You could set a cookie or request parameter and reload the page, but that may not be efficient, it calls for a lot of code server-side. More practically, you could write some javascript that iterates over your DOM, identifies target elements, and toggles some aspect of their state in conformity with the desired mode. But again, it's a lot of code, only this time on the client-side.

Or you could do the following. Use a CSS classname to identify elements that should be visible in one mode or the other. For example, ifVerbose and ifConcise.

  <body class='verboseMode'>
    <a href='/blah/blah' class='ifVerbose'>
      This is a link to /blah/blah where you 
      will discover a lot of blah.
    <a href='/blah/blah' class='ifConcise'>/blah/blah</a>

The CSS is trivial: any ifVerbose element on a conciseMode page is invisible, and vice-versa.

  .verboseMode .ifConcise {
    display: none;

  .conciseMode .ifVerbose {
    display: none;

All you need now is a tiny bit of javascript to toggle the classname of your root element between conciseMode and verboseMode.


  var verbose = function(v) {
    if (v) {
    } else {

Much less work than toggling with javascript in a big loop, no? Let the browser's CSS engine do the work!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.