How to detect if browser JavaScript is off and display a notice

2.3k views Asked by At

I need to check if browser JavaScript is off, then display a error div instead of the body, how can I do this?

4

There are 4 answers

1
roryf On BEST ANSWER
<html class="no-js">
    <head>
    <style>        
        .error,
        .no-js #container {
            display: none;
        }

        .no-js .error {
            display: block;
        }
    </style>

    <script>
        document.documentElement.className = document.documentElement.className.replace(/\bno-js\b/, '');
    </script>

    </head>
    <body>
        <div id="container">
            rest of page
        </div>
        <div class="error">
            sorry, no javascripty, no sitey!
        </div>
    </body>
</html>

Of course, this is usually a bad idea, but I hope you've already considered that.

0
Kieron On

You'll need to do it the other way around - so to speak - you'll have to output everything, and then hide/ remove the error div using Javascript.

It's called Progressive Enhancement.

0
Vinze On

in the body you can add :

<noscript>
      Here the html to display when javascript is off
</noscript>
1
johnhunter On

@roryf's solution is a good approach, although it is dependent on jQuery, and if the domloaded event fires a little late you can get a 'flash' of the no-js content.

The following will remove the html.no-js class before the body has rendered:

<!DOCTYPE html>
<html class="no-js">
<head>
<script>

if (document.documentElement) {
    var cn = document.documentElement.className;
    document.documentElement.className = cn.replace(/no-js/,'');
}

</script>
</head>