Using a no-js class in your WordPress theme

Go to source

The no-js class can often be seen in css and html, normally placed on the html or body tag. What is it all about? It’s to be able to add specific CSS styling for those who view the site with javascript disabled. How does it work? We run a simple javascript that replaces the “no-js” class with “js”. If no javascript is enabled, no-js remains. As simple as that.

To add this to your theme, first add no-js to the html-tag of your theme’s header.php:

<html class="no-js" <?php language_attributes(); ?>>

Then, add the simple javascript to replace the no-js class with js in functions.php:

/*  Script for no-js / js class
/* ------------------------------------ */
function alx_html_js_class () {
	echo '<script>document.documentElement.className = document.documentElement.className.replace("no-js","js");</script>'. "\n";
add_action( 'wp_head', 'alx_html_js_class', 1 );

And there you go. You can now add .no-js .myclass { cssfix } so that your theme doesn’t break too badly if javascript is disabled.

Originally posted 2013-11-09 19:01:30. Republished by Blog Post Promoter