views:

150

answers:

3

I want to be able to apply opacity to some elements to make them invisible only if javascript is enabled. I don't want to use display:none because I want the layout to act as if they're in the DOM, so setting opacity to 0 is perfect.

I want to be able to set this initial value using Javascript, using JQuery, so I don't have to mess with browser differences on the opacity (and many other) attributes. But if I set opacity to 0 like so:

$(document).ready(function() {
  $("#header").css("opacity", 0);
  $("#header").animate({opacity:1}, 500);
});

...half the time it's already visible on the screen, so it appears and disappears.

How do I set these css values using JQuery before they ever can render?

Looking for a JQuery only solution so I don't have to manually handle every browser implementation like this:

#header {
  -moz-opacity:.50;
  filter:alpha(opacity=50); 
  opacity:.50;
}
+1  A: 

Just set opacity to 0 in CSS file itself. To cover the scriptless, add the following to your head:

<noscript><style>#header { opacity: 1; }</style></noscript>

Update: since that's not an option, the next option would be to execute the script directly after the #header element.

<div id="header"></div>
<script>$("#header").css("opacity", 0).animate({opacity:1}, 500);</script>
BalusC
But that won't work cross browser would it? There's other browser-dependent properties I'd like to do this to also, so I'm looking for a jquery-only solution.
viatropos
@viatropos - This works cross-browser, just stick a `type="text/css"` in the style tag to eliminate any issues there. Alternatively, use a stylesheet for this, put the link in the same way.
Nick Craver
This works in all browsers from IE4 and up. With the HTML5 doctype, the `type` defaults to `text/css`. Not sure about XHTML, but it will indeed jerk about a missing `type` attribute.
BalusC
What is `-moz-opacity` and `filter:alpha(opacity)` for then?
viatropos
Add it as well then? We thought you were talking about the noscripts. It's *just* a basic kickoff example :)
BalusC
the goal is to avoid coding to browser specific implementations :)
viatropos
Well, your next option is to put that `<script>` *directly after* the `#header` element.
BalusC
thanks, I will do that!
viatropos
A: 

The problem is that JavaScript execution will almost always happen after rendering begins, unless you do a table hack that prevents rendering until the page is fully downloaded. But then you'll annoy your users, and you should be shot.

You're asking for something that just can't be reliably done without annoying the user. So your better bet is to annoy the developer, and do some extra work.

Mystere Man
makes sense, thanks :)
viatropos
+1  A: 

Why not use

#header
{ 
    visibility: hidden;
}

and then in a noscript in the head

<noscript><style type="text/css">#header { visibility: visible; }</style></noscript>
Geoff