JavaScript Detection using CSS

This is a method to see wether JavaScript is enabled using CSS. This works by giving a id(or class) to the body tag with JavaScript. With this we can set CSS rules that will only apply if javascript is enabled.

Programmers always assume that browsers that are incapable of handling CSS cannot handle JavaScript also - this is true for old browsers like lynx. But there are many paranoid people who are surfing with JavaScript turned off - but still have CSS rendering ability.

The Problem

A good example for using this is in the rating system we see everywhere - the five star rating system. For creating a gracefully degrading rating form, you have to create a form, five radio buttons and a submit button to provide the most basic rating. Then the programmer would use style to hide the form and create a new div with 5 stars for the visitor to click on. The clicking will be handled with(...drumroll...) AJAX! And all is well with the world.

The CSS code for the above example will be something like...

#rating-form {display:none;}

The problem comes when some of the fore mentioned paranoids visit the site. They have CSS - so the form will be hidden. But they don't have javascript - so the 'insert-new-div-with-images' idea will not work. The result - they will not have minimum functionality.

The Solution

The most obvious way to solve this problem is to use javascript to hide the element. Like this...

document.getElementById('rating-form').style.display = 'none';

But that is using presentation elements in the behavior layer. The puritans will have a fit if they see that.

The next option is to give the element a class and hide that class using CSS...

document.getElementById('rating-form').classname = 'hide-me';
.hide-me {display:none;}

But what happens if there is a lot of rating forms? You will have to give the classname to each element.

JavaScript Detection using CSS

So what I propose to do is give the body element a id, say, 'main-body' using javascript.


Next, using the ' '(space) descendant selector of CSS, do everything that should be done if javascript is enabled. Like this...

body#main-body #rating-form {

And all is well with the world once again.


See a very simple demo of JavaScript Detection with CSS...

JavaScript is off
JavaScript is on

Enable/Disable JavaScript and Refresh the page to see the change.

blog comments powered by Disqus