How to automatically add browser class to html in WordPress

Posted on
5/5 - (190 votes)

Quoting MDN,

Note: It’s worth re-iterating: it’s very rarely a good idea to use user agent sniffing. You can almost always find a better, more broadly compatible way to solve your problem!

That out of the way there are certain situations where you need to have the browser name automatically added to html/body element in your webpages. Ex.: Tackling blown up background images in Microsoft Edge with background-attachment: fixed and background-size: cover.

In this article I show how Detect.js library can be used to add the browser name (in lowercase) as a class to html element.

Step 1

Upload detect.min.js to your child theme’s js directory (create if not existing).

Step 2

Create a file named say, general.js in the same location having this code:

jQuery(function( $ ){

	var ua = detect.parse(navigator.userAgent);

	$('html').addClass(ua.browser.family.toLowerCase());

});

Step 3

Add the following in child theme’s functions.php:

// Enqueue Scripts
add_action( 'wp_enqueue_scripts', 'sk_enqueue_scripts' );
function sk_enqueue_scripts() {

	wp_enqueue_script( 'detect', get_stylesheet_directory_uri() . '/js/detect.min.js', '', '1.0.0', true );
	wp_enqueue_script( 'general', get_stylesheet_directory_uri() . '/js/general.js', '', '1.0.0', true );

}