Akxl Labs C# ASP.NET Articles and Tutorials Akxl Labs Web Apps and Tools for Your Website

Use JavaScript to Change or Fade Opacity/Transparency of HTML Entities

Tags tagged as   Code: CSS, JavaScript, Web
How to use CSS and JavaScript to dynamically alter the opacity of an item on a web page, including animated fade-in and fade-out of an element.

Posted August 16, 2007    Viewed 45568 times    Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Overview

This article discusses dynamic opacity transformations on HTML entities, including animated changes to fade an element in or out.

To set the opacity of an element, the CSS property to be used is the opacity property, which takes a value between 0 and 1 (inclusive). Remember that opacity is the opposite of transparency, so an opacity of 1 is visible, while an opacity of 0 is completely invisible, or 100% transparent. For compatibility with back versions of Internet Explorer, we'll also be using the filter property, which is specific to IE. The filter property uses whole number opacity values between 1 and 100. 0 is not a valid value for the filter property (but is for the opacity property), as the element will often re-render without anti-aliasing if ever set to 0.

1 .HalfOpacity 2 { 3 opacity: 0.5; 4 filter: alpha(opacity=50); /* older IE */ 5 }

Note that an opacity of 0 is different than using visibility:hidden or display:none. Unlike these settings, an opacity setting of 0 makes an element invisible but does not change the way the element interacts with other elements on the page. For example, an object with display:none, when in front of another object, does not obstruct interaction with that object. An object with opacity:0, when in front of another object, would still block you from clicking on that object or interacting with it.

Articles and downloads sponsored by:
Thanks! Amazon commissions help me pay for textbooks.

Dynamically Changing an Element's Opacity with JavaScript

Setting the opacity of an element dynamically just requires a JavaScript function that can modify the above CSS properties for an object. This function does that, and also takes into account the above logic, so all you have to do is give it a DOM object and an opacity setting between 0 and 100 (inclusive).

1 function SetOpacity(elem, opacityAsInt) 2 { 3 var opacityAsDecimal = opacityAsInt; 4 5 if (opacityAsInt > 100) 6 opacityAsInt = opacityAsDecimal = 100; 7 else if (opacityAsInt < 0) 8 opacityAsInt = opacityAsDecimal = 0; 9 10 opacityAsDecimal /= 100; 11 if (opacityAsInt < 1) 12 opacityAsInt = 1; // IE7 bug, text smoothing cuts out if 0 13 14 elem.style.opacity = (opacityAsDecimal); 15 elem.style.filter = "alpha(opacity=" + opacityAsInt + ")"; 16 }

Most of this function is just sanity-checking; only the last two lines are actually changing the opacity of the element. You can try this function out here:

Set the below image to an opacity of %.


Animating Opacity Transformations

To fade an element in or out, all we need to do is animate an opacity transformation by stepping through the SetOpacity function in frames. We can do this with the below code:

1 function FadeOpacity(elemId, fromOpacity, toOpacity, time, fps) 2 { 3 var steps = Math.ceil(fps * (time / 1000)); 4 var delta = (toOpacity - fromOpacity) / steps; 5 6 FadeOpacityStep(elemId, 0, steps, fromOpacity, 7 delta, (time / steps)); 8 } 9 10 function FadeOpacityStep(elemId, stepNum, steps, fromOpacity, 11 delta, timePerStep) 12 { 13 SetOpacity(document.getElementById(elemId), 14 Math.round(parseInt(fromOpacity) + (delta * stepNum))); 15 16 if (stepNum < steps) 17 setTimeout("FadeOpacityStep('" + elemId + "', " + (stepNum+1) 18 + ", " + steps + ", " + fromOpacity + ", " 19 + delta + ", " + timePerStep + ");", 20 timePerStep); 21 }

You simply need to call the function FadeOpacity to animate an element. The function FadeOpacityStep is a helper function that updates a single frame of the animation, but this function never needs to be directly called.

FadeOpacity requires 5 parameters to define the animation:
elemId
The id attribute of the DOM object (or HTML entity) to animate.
fromOpacity
The starting opacity for the animation.
toOpacity
The ending opacity of the animation. This is the opacity the element will have when the animation ends.
time
The time the animation should take, in milliseconds. This should be divisible by the frames per second or it will be rounded to the next highest number that is divisible.
fps
The frames per second for the animation. A higher fps value means a smoother animation, but opacity changes can be processor-intensive on larger elements, so you could lower this if needed. 8 - 12 fps is a good quality setting.

You can try this script here:

Change the opacity of the below image to % opacity over 2 seconds at 10 frames per second.


Download the JavaScript

You can download the opacityfunctions.js file here, which contains all of the examples above.


Comments & Feedback


kevin says:
Friday, April 04, 2008 @ 1:51 AM
awesome thanks
Luke says:
Friday, April 04, 2008 @ 4:45 AM
Really handy, helped me out a treat! :)
peter says:
Friday, May 30, 2008 @ 1:33 PM
thanks, great!
danny says:
Saturday, May 31, 2008 @ 1:26 PM
This thing flickers like crazy if you use it in an onmouseover/onmouseout event which makes it pretty much useless unfortunately.
Adam says:
Sunday, June 01, 2008 @ 2:53 PM
danny, it flickers because you are doing two animations at once. If you mouseout before the mouseover amination completes, the animations overlap. Animations work in frames, so an animation from 100 to 50 opacity in 5 frames does (set opacity = 90), (pause), (set opacity = 80), (pause), (set opacity = 70), (pause), (set opacity = 60), (pause), (set opacity = 50). If you overlap this with an animation that goes from 50 to 100, you intersperse frames that set the opacity to other values from the second animation, causing the opacity to 'flicker' back and forth. One animation does (set opacity = 90), (pause) but while it is paused the other does (set opacity = 50), (pause), so the opacity is flickering back and forth between them.

To fix this, you should always cancel one animation before starting another, or wait for one animation to complete before starting another. For an example technique, see my article on fading between colors in JavaScript. The code in this script was designed for use on mouseover/out, and it's structure intrinsically allows new animations to start form the point that an existing animation left off at when it was overwritten by a new request.

As a side note, when someone takes the time to write informational articles for free to teach techniques that took work to develop, you should generally ask questions when you don't understand the resources provided. I'm always happy to answer questions on the site or by e-mail and I have so far worked with everyone who has asked, but calling my code 'useless' just because you tried to use my example without taking the time to understand it (this concept was explained in the article) is hardly appropriate.
Ehsan says:
Saturday, October 11, 2008 @ 12:34 AM
Hi,Adam great work man!One thing i want to ask is
that i want to run a function after completion of this fade effect but the function is executed instantly. e.g

FadeOpacity(....);
HideElement(...);

HideElement is called instantly while fading continues in the backgroud.
I will appreciate any help.
Thanks again
Adam says:
Wednesday, November 19, 2008 @ 11:53 AM
Ehsan, try this:

FadeOpacity(...);
setTimeout(function() { HideElement(...); }, 1000);

adjust the 1000 so that it matches the time parameter to FadeOpacity. setTimeout will cause HideElement to be run after the time period (1000 milliseconds in the example above) is up, allowing your animation to run and HideElement to wait and run after the animation is finished.
Sharad Saxeana says:
Monday, March 30, 2009 @ 10:32 PM
Hey......Adam...Thankxx A lot.
I was searching for this on google....Fortunately i found ittt..It will do wonders for me

Thanxx againnn !!!
Mani says:
Sunday, May 10, 2009 @ 9:46 AM
Really Awesome
Thanks
Kenneth Horan says:
Wednesday, May 27, 2009 @ 7:09 PM
Thanks...this was exactly the information I needed!
Sarah says:
Tuesday, October 20, 2009 @ 1:13 PM
Thanks! This was very informative.
David says:
Sunday, November 15, 2009 @ 6:41 AM
Thanks for this! Having the interactive examples really helped me to understand how opacity works in javascript.
decibel.places says:
Sunday, November 29, 2009 @ 4:01 PM
This works well for img elements but I am having problems applying the technique for IE7 and IE6 to other elements, eg div.

For some reason, testing on this page, I could only set opacity dynamically for h2 elements in IE<8, and I thought because opacity was set in stylesheets for h2 but it appears not.

?????
jonathan says:
Thursday, December 03, 2009 @ 10:01 AM
Decibel, try setting the width and height of the div or whichever element to 100%, images come with predefined widths and heights, divs don't
Leave this field blank:
Comment on this Entry
This work is licensed under a Creative Commons Attribution 3.0 United States License.
Please link to this article in your source code comments if you use this content.

Labs

Blog

The blog has moved.
Non-technical articles are now on a seperate site.
Contact me for the new address.

Apps

Real-Time Coffee Counter
add it to your website!
Golden Ratio Visualizer
a tool for design

Coffee Counter

Current Count:
Akxl Coffee Meter
Current Coffee:
 Peet's Malawi Songwe River

The Real-Time Coffee Meter is a free Website App from Akxl Labs. Text-only and badge versions available.