Identify and add web browser name as body class using jQuery

There a few cases where you want to identify and target a specific web browser because for example you’re CSS isn’t rendering well on this particular browser. And I’m not point any fingers to a specific browser 👉 ..** IE ** .. 👈

Using the jQuery code snippet below you will add the used web browser as a custom body class.

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 = window.navigator.userAgent.indexOf('MSIE'),
            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 > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
            hoolite_body.addClass('is-ms-explorer');
        }
        if (/Edge\/\d./i.test(navigator.userAgent)) {
            hoolite_body.addClass('is-edge');
        }
    }
});

That’s it!

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.