Posted on

Detecting Javascript in WordPress

Let’s keep this post short and to the point. We build these fancy full screen menus or accordions but do they work if Javascript is disabled or it doesn’t load. In my opinion they should work.

In most cases I have used method seen in Twenty Sixteen WordPress theme. It has three steps.

Step 1: Add no-js class to html element

Add no-js class to html element which is usually in header.php file.

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

Step one done. In the next step we change no-js class to js class if Javascript is detected.

Step 2: Add Javascript detection

In your themes functions.php file (or custom plugin) add this code:

/**
 * Handles JavaScript detection.
 *
 * Adds a js class to the root <html> element when JavaScript is detected.
 *
 * @since Twenty Sixteen 1.0
 */
function twentysixteen_javascript_detection() {
	echo "<script>(function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement);</script>\n";
}
add_action( 'wp_head', 'twentysixteen_javascript_detection', 0 );

It adds Javascript in the <head> element and change no-js class to js class if Javascript is detected.

Step two done.

Styles using no-js or js classes

Rest is totally up to you. Now you can use classes no-js and js classes however you want and for example Foundation accordion works nicely even without Javascript.

One comment Detecting Javascript in WordPress

Comments are closed.