Question

I am trying to build a progressively enhanced page that works for JS and non-JS users. I would like to hide some form controls initially for JS users, but always show them for non-JS users.

My question is about how to do this without creating a distracting "visible, then instantly hidden" flash of content for JS users.

For example, in the JS version, I want to collapse part of my search form, and instead show a 'click here for extra options' button. I do this as follows:

$(document).ready(function() { 
  $("#extra-options").hide();
  ...
  $("#show-extra-options").click(function() { 
     $("#extra-options").slideToggle();
  });
});

This works, but it means that for JS users, when the page loads, the extra options are visible for 500ms or so, then they vanish. It's rather distracting.

Is there any sensible way to get around this?

StackOverflow has just suggested this answer: is this sensible? Sorry if this is now a duplicate question, but I figure it's still worth writing this question in my own language, as I didn't find the answer during searching.

Was it helpful?

Solution

Add this in your script tag in the head:

$('html').addClass('js');

Then you can use that to show and hide elements:

.hasJs { display: none; }
.js .hasJs { display: block; }
.js .noJs { display: none; }

You can hide content for either users with or without Javascript:

<div class="hasJs">Some content only visible for JS users.</div>
<div class="noJs">Some content only visible for non-JS users.</div>

As the class and CSS are in the head, the elements will already be styled when they come into existance when the body is parsed.

Demo: http://jsfiddle.net/Guffa/YuAyr/

This is a similar approach to the one in the first answer to the question that you linked to, but this is somewhat cleaner because you don't have to add a class to the html element in the markup, and the code simply adds the class instead of removing it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top