No JavaScript Variants in Tailwind CSS
Most modern web development projects require JavaScript, but what do you do when clients specifically disable it? Yes, you can always provide a fallback, but it’s not easy to toggle without configuration. In Tailwind, you can create a variant that increases specificity on certain elements when the no-js
class on the html
element.
In my projects, I will add this class to elements to hide specific elements.
<div class="no-js:hidden">...</div>
It doesn’t have too much use, but it’s a nice-to-have when you need it.
To do this, you have to add the no-js
class directly to the HTML element and an inline script that will remove or replace the no-js
class. I prefer to replace it with a js
class to indicate that JavaScript is enabled, but you can remove it if you like.
<html class="no-js">
<head>
// ...
<script>
document.documentElement.classList.replace('no-js', 'js')
</script>
</head>
</html>
And you have to add an additional plugin to your tailwind.config.js
file that will add a no-js
variant.
plugins: [
function ({ addVariant, e }) {
addVariant('no-js', ({ modifySelectors, separator }) => {
modifySelectors(({ className }) => {
return `.no-js .${e(`no-js${separator}${className}`)}`
})
})
},
]