Mazzarolo MatteoMazzarolo Matteo

The opposite of the noscript element

By Mazzarolo Matteo


This post is a short ode to a StackOverflow answer.

The <noscript> HTML element defines a section of HTML that will be parsed and shown to the user only if JavaScript is turned off in the browser.

This element is what allows web pages to warn you with "Please enable JavaScript" messages:

But what if you wanted to achieve the opposite of <noscript>?
How do you display a website section only if JavaScript is enabled?

More than ten years have passed, and I still think this StackOverflow answer is the most elegant way to support this use case. It takes advantage of <noscript> to tell browsers that don't have JavaScript enabled to hide the content you're interested in using CSS.

To do so, add the following in the <head> of your web page:

<noscript>
  <style>
    .js-only {
      display: none;
    }
  </style>
</noscript>
<noscript>
  <style>
    .js-only {
      display: none;
    }
  </style>
</noscript>

That's all. You can now apply the js-only class to all elements you want to show only when JavaScript is enabled.

I come back to this solution often, and I love how elegant and simple this approach is: no messing around with JavaScript, no layout shifts. Just plain and simple CSS.