Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide html only when Javascript is available

I guess this is more about SEO than wanting to support browsers with Javascript disabled. I have Javascript/jQuery code that reads in some html and basically displays it much nicer. The html is actually removed (with jQuery's .remove() function) during the process.

So I hide the html so there aren't any visual artifacts as the page loads. But now I want to only hide it if Javascript is enabled. I guess the easiest thing is to have some Javascript in <head> that adds the display: none css rule to the appropriate elements.

Is there a better way for dealing with this situation?

like image 790
at. Avatar asked Feb 10 '26 15:02

at.


2 Answers

I think using noscript html tag will do the job. The tag displays the content inside if the script is disabled in users browser.

like image 142
katsuya Avatar answered Feb 12 '26 16:02

katsuya


Any JavaScript will only work if JavaScript is enabled so no matter how you do it using JavaScript it will always work only if JavaScript is enabled so you never have to test for that.

That having been said, you can see how it is done in the HTML5 Boilerplate:

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

using a no-js class applied to the <html> tag. The class is later removed using JavaScript and a js class is added, both of which you can use in your CSS and HTML:

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

Or in CSS:

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

If you're using Modernizr then it will already change those classes for you, but even if you don't then all you have to do is something like:

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

It's a simple and elegant solution and all you have to worry about is CSS classes in your styles and markup.

like image 35
rsp Avatar answered Feb 12 '26 16:02

rsp