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?
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:
using a
no-js
class applied to the<html>
tag. The class is later removed using JavaScript and ajs
class is added, both of which you can use in your CSS and HTML:Or in CSS:
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:
It's a simple and elegant solution and all you have to worry about is CSS classes in your styles and markup.
I'd probably use a single bit of script that sets a class on body you can then reference in your CSS, but basically, you're on the right track.
E.g.:
Then your CSS rule:
The rule will only kick in if the body has the class.
Complete example:
HTML (and inline script):
CSS:
Live copy I've only used the "foo" class for an example. It could just as easily be a structural selector.
Add the class
hiddenblock
to each div (or block) you want to hide, and add this JS code in the header:You can also use the class
jsenable
to mask or modify some other block, like this:I think using noscript html tag will do the job. The tag displays the content inside if the script is disabled in users browser.