Camel Punch - Brighton-based web development

Leverage CSS

Graceful hiding

Hiding or showing content for JavaScript enabled or non-JavaScript enabled browsers has a lot of uses. For example, you can hide certain submit buttons in CSS if you know JavaScript will trigger form submission. Such stuff happens quicker and is easier to maintain in CSS.

The noscript approach

I prefer to place a linked stylesheet into a <noscript> element for the few browsers that are not using JavaScript. This will add to download time for those users, but for the majority JavaScript-enabled browsers, you can write your standard CSS without thinking about the non-JavaScript cases. Then, when you're ready to write your non-JavaScript stylesheet, fill your noscript CSS file with the necessary overrides for non-JavaScript browsers.

<noscript> 
<link href="/stylesheets/noscript.css" media="screen" rel="stylesheet" type="text/css" /> 
</noscript>

This has the benefit over the dynamic body class approach of removing the short delay that you might experience when waiting for the JavaScript class to be added.

The dynamic body class approach

For this approach, I stick something like the following after the DOM ready line (this is jQuery speak):

$('body').addClass('javascript');

Lazy dual render

If you're lazy or don't want to render markup from JavaScript, you can render both JavaScript and non-JavaScript interfaces in your markup (if they differ), then switch to the appropriate one depending on whether the body element has the 'javascript' class.

 
   
.javascript #some_element_for_non_js_users_id { display:none }
#some_element_for_non_js_users_id { display:block }
   
  

Get semantic

I try to use JavaScript to change class names, then use CSS to change the appearance of the element, rather than hardcoding colours and so on in JavaScript source code.

For example, if an element has different statuses depending on user interaction, then all the JavaScript has to do when the action is performed is change, add or remove a class.

I set rules for the class in CSS and proceed to be surprised when I can reuse the class colour rules elsewhere on the site (CSS is meant to be a stylesheet language, after all).

I believe this will execute faster, too, providing your users with a snappier response time.

About the author

This tutorial's author is Andrew Bruce, who writes:

I often see people tearing their hair out wondering how to change the basic appearance of something with JavaScript. Don't bother - just change the class! This is a page for tips such as these.