Mike's corner of the web.

Archive: CSS

The opposite of <noscript>

Saturday 9 June 2012 21:49

HTML has the <noscript> tag for when you want an element to be displayed if and only if JavaScript is disabled, but what if you want the opposite? How do you display an element if and only JavaScript is enabled? I came across a rather tidy solution on StackOverflow. In the <head>, we add the following:

<noscript>
  <style>
    .iff-javascript-enabled {
        display: none;
    }
  </style>
</noscript>

We then add the iff-javascript-enabled class to the appropriate elements:

<noscript><p>JavaScript is disabled</p></noscript>
<p class="iff-javascript-enabled">JavaScript is enabled</p>

The advantage of this solution over others is that there's no delay. Most other solutions hide the relevant elements by default, and then use JavaScript to show them, but this means that the elements are hidden until that piece of JavaScript fires. However, in some cases this is desirable. For instance, suppose an element does nothing until some JavaScript hooks up an onclick handler. Showing that element before the onclick handler is added might be frustrating since clicking the element would do nothing.

Still, there's a simplicity to this solution that I quite enjoy.

Topics: HTML, CSS, JavaScript