I’ve been doing a lot of reading and coding for non-JavaScript users. GradeMate was fully converted to degrade gracefully for all people who do not have JavaScript enabled. While I’m usually one to promote the use of new technologies (JavaScript is incredibly old too) I feel that a website should not force users to enable it. It’s also the mark of a clever and thoughtful programmer.

One of the struggles here is to provide a way to show and hide content among non- and JavaScript enabled users. The method I previously employed was to have two classes: .js-hide and .css-hide. The first one .js-hide was called in JavaScript when the document was ready to hide all instances of this class and to show all instances of .css-hide (I’m using jQuery).

  1. $(“.js-hide”).hide();
  2. $(“.css-hide”).show();

The problem with this approach is that you will see the elements that I want to hide as the page is loading, and then they’ll disappear once my $(document).ready() triggers. While it’s slight, it’s still something I don’t want.

To get around this, I’ve used the <noscript> tag. So, now my CSS file stays the same - it hides everything in those classes. My JavaScript file looks like this:

  1. $(“.css-hide”).show();

The only thing I had to include is the following lines in my header HTML file:

  1. <noscript>
  2. <style type=“text/css”> .js-hide { display: block; } </style>
  3. </noscript>

The elements that I don’t want my non-JavaScript users to see remain hidden as the JS never loads. However, the elements I want hidden for JS users hide before they’re rendered so we don’t see them for that time before the JavaScript triggers. And finally, these elements which my non-JavaScript users would normally not see, are now visible since it triggers from the <noscript>.

There’s two things to note here, however. First, I’m setting the hidden elements to display: block;. If you have elements that need to be inline or some other display type, I would suggest making two or more classes to accommodate them. Just .inline-hide or .table-cell-hide would work. Second, you need to put your CSS definitions at the bottom of the CSS file. They need to be applied last. Also, do not put a !important attribute to them in the CSS as the jQuery code to show them will not work.

Anyway, it works out pretty well and in very few lines of code. Let me know if anyone has any alternative ideas.

Showing/Hiding Content for Non-JavaScript Users was posted on Tue, 9 February 2010 at 11:25:59

0 Comments

Post a Comment

What is 5+3? (Anti-spam)
Ahh, my 9th symphony. I've arranged this piece for xHTML, CSS, PHP and MySQL. It should sound beautifully across all instruments, and was meticulously prepared with standards and accessibility in mind. View the Colophon, or contact me. All material © 2010 Mike Gioia, et al.