JavaScript aware CSS

Let your CSS know if JavaScript is enabled or disabled by first adding a class to the html tag and then change it using JavaScript.

Why?

You want to give the best possible experience to both JavaScript and non-JavaScript users. Let's say you have a partially collapsed text with a JavaScript based "Read more" button. Of course you want the whole text to be visible if JavaScript is disabled. At the same time you want to avoid the flickering that might occur if JavaScript is used to hide the text. Chances are then that a CSS selector expression that only triggers if JavaScript is enabled will make you happy. :)

How?

In the following example a border is set on one of the two paragraphs in the body. The first one gets a blue border if JavaScript is enabled and the second one gets a red border if JavaScript is disabled.

  1. <html class="noscript">
  2. <head>
  3. <title>JavaScript aware CSS - example 1</title>
  4. <script>
  5. document.documentElement.className = 'script';
  6. </script>
  7. <style>
  8. .script .one { border: 3px solid #00f; }
  9. .noscript .two { border: 3px solid #f00; }
  10. </style>
  11. </head>
  12. <body>
  13. <p class="one">Blue border when JavaScript is enabled.</p>
  14. <p class="two">Red border when JavaScript is disabled.</p>
  15. </body>
  16. </html>

You can try out example 1 here.

If you already have another CSS class in the html tag you will have to alter the script part to something like this instead:

  1. document.documentElement.className = document.documentElement.className.replace( 'noscript', 'script' );

In example 2 you will se the use of a JavaScript "Read more" button, where the whole text is visible immediately if JavaScript is disabled. In order to achieve the sliding effect the jQuery JavaScript library is used as well.