views:

428

answers:

4

I want to turn down the opacity on an element when a user performs an action.

The current code I have is:

document.getElementById('MyOpaqueElement').style.opacity = 0.3;
// There are checks in the real code for NULL, etc.

This works on Firefox, Safari, etc. IE8 has different ideas about opacity. I have read a couple of articles but have yet to find a definitive answer on the most portable method to do this in a cross-browser way.

+2  A: 

There are various browsers-specific settings and notations you need to take into consideration.

See Quirksmode.org: CSS2 - Opacity

I suggest using a Framework like JQuery, Prototype, MooTools or Dojo. I know it seems ridiculous to add dozens of kilobytes of code just for some opacity at first, but it's really worth it. It just works in one way for all browsers.

Pekka
I am already using JQuery (obviously not enough). I don't see a direct opacity feature. Can I add opacity $('XXX').css('opacity',0.3); or should I append another class to the element (Not sure how to do that).
Martin York
There's `$(element).fadeTo(0, 0.5);` See http://docs.jquery.com/Effects/fadeTo#speedopacitycallback but there may be something even more elegant around.
Pekka
A: 

It possible to achieve this via jquery. Check the following stack overflow post:

http://stackoverflow.com/questions/1543745/jquery-opacity-change

deostroll
+1  A: 

EDIT- Poster is using jquery..

Easy way:

  $(el).css('opacity' '0.3');

(I checked the jquery sources, and it handles opacity for cross-browser compatibility automatically, so that should work)

Or for a CSS solution: Just give it a class, e.g. 'transparent', and add this to your CSS file:

.transparent {
    filter: alpha(opacity=30); /* for IE */
    -khtml-opacity: 0.3;      /* khtml, old safari */
    -moz-opacity: 0.3;       /* old mozilla, netscape */
    opacity: 0.3;           /* good browsers: FF, safari, opera */
}
Infinity
A: 

The equivalent should be document.getElementById('MyOpaqueElement').style.filter = 'alpha(opacity=30)';

By the way, even if you don't use a library like YUI or JQuery, you can download them and search their sources for the word

opacity

.

Gyuri