Flash of Jquery hidden content before JS is called to hide it

17th August, 2011 in Technical 2 Comments

This applies to when you use Jquery to hide an element, and not the CSS. What happens is the element you want to hide in Jquery briefly gets shown after the page is rendered and before the JQuery is called to hide it.

A common solution is just hide the element in the CSS. The problem then is people with JS disabled browsers will not be able to see the content, because they don’t have JS to show it.

I found a great solution online (http://oncemade.com/adding-hasjs-class-when-javascript-is-available/).

Add in a line of Javascript at the top of the page to add a class to the HTML tag. Then in your stylesheets you can hide the elements, referencing the JS added tag in the HTML.
e.g.
// In your HTML <head>

<script type=”text/javascript”>document.getElementsByTagName(‘html’)[0].className+=’js’</script>

// In your Stylesheet

.js .myHiddenElement
{
    display: none;
}

Now JS disabled browsers will see the content, and JS enabled browsers will hide it before the page is rendered by referencing the JS added class in the <html> tag.
Brilliant

Comments
Picture of Paul Gassoway

Paul Gassoway 18th July, 2013 at 18:36 pm

I was successful with this technique. It worked very nicely since my index.html only required the one JavaScript line.

Just some clarifications that would have helped me:

The stylesheet should have two .myHiddenElements, when there was one. So if your CSS contains:

.myShownElement {

display: block;

}

.myHiddenElement {

display: none;

}

You should change it to look like this:



.myShownElement {

display: block;

}

.js .myHiddenElement {

display: block;

}

.myHiddenElement {

display: none;

}



So when the html block has the .js class, the .js .myHiddenElement is given precedence. When there is no .js class, the .js .myHiddenElement doesn't match. Fortunately, .myShownElement works the same either way.

Picture of Paul Gassoway

Paul Gassoway 18th July, 2013 at 18:40 pm

Apologies, there's a typo in my comment above. The new CSS should look like this:





.myShownElement {

display: block;

}

.js .myHiddenElement {

display: none;

}

.myHiddenElement {

display: block;

}



The .myHiddenElement's above were switched. You want the .js element to work the way you want when JavaScript is enabled, and the non-.js element to work the way you want when JavaScript is disabled.

Leave a Reply

Recent