Question

I often find myself showing/hiding elements with jQuery, for example a simple tabbed content area where the first tab is visible and the others are not until they are displayed with the javascript. I know it's not good practice to hide the initially hidden ones using CSS (display: none) and then showing the correct ones with JS as non-JS users will never see a thing. So by default I show all and then hide the relevant ones with JS.

In doing this though, the hidden elements will load and then only hide when document is ready. How can I stop this happening? Is there a way of doing this in a way that will degrade gracefully but also not have elements appearing whilst loading, and then promptly disappearing as this looks a bit shoddy.

Was it helpful?

Solution

a few thoughts...

If you don't mind jQuery being littered all over the page as opposed to being all in a separate file, you can call $('#divToHide').hide(); immediately after the element appears. Not very good practice though. Although it depends on the use case, if you are largely a designer/themer creating a 5 page brochure site, you should choose what is right for you!

Or if you're a bit more of a techie, you might like to mess around with .live()/.livequery() and catch the element's insertion with JS and hide is straight away. See this post Is there a jquery event that fires when a new node is inserted into the dom?

OTHER TIPS

Unfortunately, the way that Javascript works, this doesn't seem to be possible. There will always be a fraction of a second between the first rendered frame and by the time the JavaScript to hide the element gets executed I was wrong about that, jQuery seems to be able to do that. So, CSS is the best means for this. Luckily, you can add an alternate CSS stylesheet within an infamous <noscript> tag:

<style type="text/css">
    #jquery-thing {
        display: none;
    }
</style>
<noscript>
    <style type="text/css">
        #jquery-thing {
            display: block !important;
        }
    </style>
</noscript>

Here's the JSFiddle link: http://jsfiddle.net/kylewlacy/dbWuc/

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