Skip to main content
kld.dev

CSS utility classes that detect JavaScript

This is a neat pattern that I picked up years ago. Have you ever thought (or dreamed) of putting a <style> block inside a <noscript> block? You can, and you should.

Noscript? Noproblem

If you want to hide a button whenever JavaScript is disabled, you can totally do that.

<noscript>
  <style>
    button.the-button {
      display: none;
    }
  </style>
</noscript>

If you are building a resilient site that has to work with or without JavaScript, you can take advantage of this to create some convenient utility classes.

Keep it classy

Here are some classes I use that follow the Tailwind variant naming convention (e.g. sm:hidden, hover:bg-black, etc.). They are defined within my HTML’s <head> section.

<head>
  <noscript>
    <style>
      .nojs\:hidden {
        display: none !important;
      }
      .nojs\:block {
        display: block !important;
      }
      .nojs\:flex {
        display: flex !important;
      }
      .nojs\:grid {
        display: grid !important;
      }
      /* ... inline, inline-block, etc. as needed */
    </style>
  </noscript>
</head>

I can then show or hide elements based on whether JavaScript is enabled, and I don’t have to add any more <noscript> tags or additional JavaScript.

<button class="nojs:hidden">Do JavaScript</button>

<button class="hidden nojs:inline-block">Do non-JS stuff</button>

Use cases

I could probably think of a million uses for this if someone locked me in a cell and forced me to do so. It would be the most boring Saw sequel since Saw V.

  • Hiding a “Copy to clipboard” button when JavaScript is disabled
  • Showing a search button next to a search input that would otherwise search as you type
  • Similarly, showing a submit button for a form that would otherwise do a fetch after input, change, or blur events
  • Hiding loading spinners
  • Hiding live chat support, custom video players, interactive data visualizations, and all those other gizmos
  • And although this approach might be overkill for it, I have to include the dreaded “You must enable JavaScript to use this site.”

Bonus tip

In case you were not aware, you can enable and disable JavaScript in Chrome DevTools for testing purposes:

  1. Press Cmd+Shift+P or Ctrl+Shift+P to open the Command Menu.
  2. Start typing javascript, and select the Disable JavaScript or Enable JavaScript command.
  3. Press Enter. You will see a little exclamation triangle icon on the Sources tab while JavaScript is disabled.
  4. Reload the page.

Bonus to the bonus tip

In Firefox DevTools, the Disable JavaScript command can be found in the Debugger tab’s gear menu.

Webmentions

Kevin Lee Drum
@amxmln Another one for the tool belt! Thanks!
Amadeus Maximilian
@kevinleedrum it’s also great if you do something like fading out lazy-loaded images until they’re available. ????