1

From a widest compatibility with various browsers perspective, what is the best way to show content for only JavaScript enabled clients? There have been similar questions, however, they are old and in conflict.

I have seen other options, however, it seems like these two are the best?

<!DOCTYPE html>
<html>
    <head>
        <title>anti-noscript</title>
        <noscript><style> .yes_script1 { display: none } </style></noscript>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js" type="text/javascript"></script>
        <script type='text/javascript'>
            $(function(){
                $('.yes_script2').show();
            });
        </script>
        <style>
            .yes_script2{display:none;}
        </style>
    </head>
    <body>
        <p class="yes_script1">Show to JavaScript clients only.</p>
        <noscript>Show to non-JavaScript clients only.</noscript>
        <p class="yes_script2">Show to JavaScript clients only.</p>
    </body>
</html>
Community
  • 1
  • 1
user1032531
  • 24,767
  • 68
  • 217
  • 387
  • Insert the content with Javascript, or hide it with CSS and show it with Javascript. – Peter Olson Jan 27 '14 at 14:58
  • Load everything reliant on JS using XMLHttpRequest? It'll be slow and fragile (it's how the Twitter website used to work before they realised just how slow and fragile it was) but it'll only work if script is enabled and allowed. – Olly Hodgson Jan 27 '14 at 14:59
  • @Peter. Why don't you recommend the `noscript` in the head solution? – user1032531 Jan 27 '14 at 14:59

1 Answers1

2

Actually, you linked a pretty good answer in your question: https://stackoverflow.com/a/431554/2373138

<head>
    <noscript><style>.jsonly { display: none; }</style></noscript>
</head>
<body>
    <div class="jsonly">javascript users only</div>
</body>

Another common solution is to use javascript itself for that:

<head>
    <style>
        .jsonly { display: none; }
        .js .jsonly { display: block; }
    </style>
</head>
<body>
    <script>
        document.body.className = "js";
    </script>

    <div class="jsonly">javascript users only</div>
</body>

DEMO

However, this solution will fail for inline elements, because it will override the display property, but here's a fix, just replace the CSS before with the following:

body:not(.js) .jsonly { display: none; }

DEMO

Community
  • 1
  • 1
kelunik
  • 6,750
  • 2
  • 41
  • 70