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;
}

3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

7 Comments

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 - 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.
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.
What is -moz-opacity and filter:alpha(opacity) for then?
Add it as well then? We thought you were talking about the noscripts. It's just a basic kickoff example :)
|
1

Why not use

#header
{ 
    visibility: hidden;
}

and then in a noscript in the head

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.