How to Add Web Browser Names as Body Classes in WordPress Using jQuery

When it comes to web development, knowing the web browser of your site’s visitors can help you create a better user experience. You may want to add specific styles or functionality for certain browsers or troubleshoot issues that only occur in certain browsers. One way to accomplish this is by adding the web browser name as a body class in your WordPress site using jQuery. In this tutorial, we’ll walk through the steps to identify and add the web browser name as a body class in WordPress using jQuery.

This code will identify whether the user is browsing with Chrome, Safari, Firefox, Internet Explorer, Edge, or Opera. You can modify this code to add support for other web browsers as needed.

For example: <body class="is-chrome">

(function ($) {
    // Document ready.
    $(function () {
        hooliteBrowserDetection();
    });
    // Browser detection.
    function hooliteBrowserDetection() {
        var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor),
            isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor),
            isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1,
            isIE = /MSIE/.test(navigator.userAgent) || /Trident/.test(navigator.userAgent),
            isEdge = /Edge/.test(navigator.userAgent),
            isOpera = /OPR/.test(navigator.userAgent) && /Opera/.test(navigator.vendor),
            hoolite_body = (jQuery('body'));
        if (isChrome) {
            hoolite_body.addClass('is-chrome');
        }
        if (isSafari) {
            hoolite_body.addClass('is-safari');
        }
        if (isFirefox) {
            hoolite_body.addClass('is-firefox');
        }
        if (isIE ) {
            hoolite_body.addClass('is-ms-explorer');
        }
        if (isEdge) {
            hoolite_body.addClass("is-edge");
        }
        if (isOpera) {
            hoolite_body.addClass("is-opera");
        }
    }
});

And that’s it! With these simple steps, you can easily add web browser names as body classes in WordPress using jQuery. This can be a useful tool for customizing your site’s appearance and functionality based on the web browser that your users are using.

Support 🐶

If you found this article helpful, got a question or spotted an error/typo... Do well to leave your feedback in the comment section or help spread it by sharing this article. If you're feeling generous (and I hope you do) you can definitely help me by getting me a cup of coffee ☕.


You may like these too!

Leave a Reply

Your email address will not be published. Required fields are marked *