Add Class To <body> If JavaScript Is Enabled

This snippet is super small but is super handy. It detects to see if JavaScript is enabled on the users browser. If yes, a class will be added to the <body> tag


 $('body').addClass('yourClassName');

Adds the class yourClassName to <body> tag if Javascript is enabled.


<body class="yourClassName">

2 Comments

  1. If you add the following code just after your <body> tag you can remove the dependency on jQuery being loaded and move the jQuery include to the bottom of the page (better for perceived page load)…
    It basically mirrors what Modernizr does but I use it on projects where I amn’t using Modernizr…Just add a “no-js” class to your <html> tag and if JS is enabled it replaces it with “js”.

    <script>
    (function(doc, classToAdd){
       doc.className = (doc.className).replace("no-js", classToAdd);
    })(document.documentElement, "js");
    </script>
    
  2. This is jquery not javascript..

This post currently has 2 responses. What do you think?

You can use basic HTML when posting code, please turn all < characters into &lt; or > into &gt;
If the code is multi-line, use <pre><code></code></pre>

Leave a Reply

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