Question

I have a function shoh() which is toggles the state of a div - either showing or hiding it. When a page is loaded, shoh($id) is repeatedly called for each div to hide on the page by changing the style to display:none. If the user wants to see the data in the hidden div, they click on a link with onClick="show($id)" to change the div style to display:block.This all works great.

I want the page to work even if javascript is disabled, so I have to have the divs default to visible or else a user without javascript will never be able to see the data. The problem is that when the page loads, all the divs are displayed visible and the page needs to completely load before the divs are hidden. This is aesthetically poor and creates visual confusion as the page can take a couple of seconds to load.

Is there any way to prevent the screen from displaying the divs until after the javascript has had a chance to run? I wouldn't mind display "Loading..." or something. Thanks in advance.

//toggle state of div - show OR hide - default is hidden
function shoh(id, cmd) { 
// if cmd is not blank, clicked on button to expand all or collapse all
cmd = typeof cmd !== 'undefined' ? cmd : '';
if (document.getElementById(id)){
    if ((document.getElementById(id).style.display == "none" || cmd=='show') && cmd!=='hide'){
        //show
        document.getElementById(id).style.display = 'block';
        filter(("img"+id),'imgin');
        setCookie(window.location.pathname + ":" + id, "show", 365)
    } else {
        //hide
        document.getElementById(id).style.display = 'none';         
        filter(("img"+id),'imgout');
        deleteCookie(window.location.pathname + ":" +id);
    }   
}   
}
Was it helpful?

Solution

Use document.write to wrap the whole thing in a div that is not shown and then show it in JavaScript. If the client doesn't have JS, then neither the document.write will be rendered and the final call to show it won't be needed.

Put this script inline, not in a header..

<script type='text/javascript'>
    document.write("<div id='hideWhileRendering' style='diplay: none;'>");
</script>

... then rest of your divs ...

<script type='text/javascript'>
    document.write("</div>");
</script>

then use an onload function to change the display to show. If no JS is run, then all of this will get ignored. If JS is run, then it'll be all invisible until onload is finished.

OTHER TIPS

Put CSS that makes the DIV visible inside <noscript>:

<style>
    #hideWhileRendering {
        display: none;
    }
</style>
<noscript>
<style>
    #hideWhileRendering {
        display: block;
    }
</style>
</noscript>

The second style block will override the first one, but only when JS is disabled.

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