GreatWebGuy Self-proclaimed greatness is a hard thing to prove.

22Apr/0920

Enable JavaScript specific CSS with one line of jQuery

jQuery is by far my favorite JavaScript framework in terms of simplicity and just pure DOM power. I picked up a little trick at a conference quite a few months back and improved upon it and thought it could benefit anyone that believes in the mantra of progressive enhancement. Here's the line of code that will change the way you develop your applications.

$("html").removeClass("nojs").addClass("js");

Obviously jQuery is a requirement here. The other thing you'll need to do is add a class of nojs to the html node of all of your documents/templates.

<html class="nojs">

Now you're ready to change the way you write your CSS. I'm aware that Yahoo/YSlow recommend that you stick your JavaScript at the bottom of the page, but this little trick won't work as well unless jQuery and the snippet above are in the head of the html document. Now what this buys you is the ability to style your document with separate elements for javascript enabled users, non-javascript users and common elements that both will need. You'll be able to hide/show substitute elements in the page that are dynamic in nature so that you can successfully implement a site using progressive enhancement, meaning that users with javascript disabled will still be able to use your site but without all the bells and whistles. This also prevents the flicker that you see on page load when you modify elements via DOM manipulation using JavaScript.

Now you can write CSS like this:

.nojs a.myclass {color:red}
.js a.myclass {color:black}
a.myclass2 {color:blue}

In this very simple example all of your non-javascript users would see links with a class of myclass as red and all javascript enabled users would see the links with the color black. Both javascript and non-javascript users would see the links with the class myclass2 as blue.

This very simple example opens hundreds of possibilities for the way you style your site. You could actually display and hide content based on whether javascript is enabled or not, including buttons and links or any element on the page. You could include text for Search Engines and Screen Readers that your regular users might not need to see because the nature of the content could be for SEO or descriptive purposes for non-javascript users. You could also use it to enhance your suckerfish CSS menus with a hoverIntent when javascript is enabled making your menus a little more user friendly.

I realize this technique could be implemented with just about any JavaScript framework, jQuery just happens to be my framework of choice and this technique has definitely given us much capability to target javascript/non-javascript users and unobtrusively progressively enhance our website.

Please see my latest article on implementing this without a JavaScript framework.

Tagged as: , , 20 Comments