Hide html only with Javascript

I think this is more about SEO than about the need to support browsers with Javascript disabled. I have Javascript / jQuery code that reads in some html and basically displays it much nicer. Html is actually deleted (with jQuery function .remove()) during the process.

So, I hide html so that there are no visual artifacts on the page. But now I only want to hide it if Javascript is enabled. I think the easiest way is to have Javascript in <head>, which adds a display: nonecss rule to the relevant elements.

Is there a better way to handle this situation?

+3
source share
4 answers

JavaScript , JavaScript , , JavaScript, , JavaScript , .

, , HTML5 Boilerplate:

<html class="no-js" lang="en">
... the rest of the page
</html>

no-js, <html>. JavaScript js, CSS HTML:

<p class="js">This is displayed if JavaScript is enabled</p>
<p class="no-js">This is displayed if JavaScript is disabled</p>

CSS:

.no-js #someWidget { display: none; }
.js #someFallback { display: none; }

Modernizr, , , , - :

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

, , , - CSS .

+2

, noscript html tag . , script .

+5

, , script, , CSS, , .

:.

<body>
<script>document.body.className = "jsenabled";</script>

CSS:

body.jsenabled selector_for_your_initially_hidden_content {
    display: none;
}

, .

:

HTML ( script):

<body>
  <script>document.body.className = "jsenabled";</script>
  <div class='foo'>I'm foo, I'm hidden on load</div>
  <div>I'm not foo, I'm not hidden on load</div>
  <div class='foo'>Another foo</div>
  <div>Another bit not hidden on load.</div>
</body>

CSS

body.jsenabled div.foo {
  display: none;
}

"foo" . .

+2

Add a class hiddenblockto each div (or block) you want to hide, and add this JS code to the header:

$(document).ready(function() {
    $(body).addClass('jsenable');
    $('.hiddenblock').hide();
}

You can also use the class jsenableto mask or modify some other block, for example:

.jsenable #myblock { position: absolute; right: 10000px; }
0
source

All Articles