Opacity Plugin for jQuery

About 5 minutes ago, I was in need of a .opacity function for jQuery, so I whipped this up:

/**
* Opacity function for jQuery
*
* @name .opacity
* @cat Plugins/Effects
* @author Woody Gilk/woody.gilk@gmail.com
*
* @example $(this).opacity(.2);
*/
$.fn.opacity = function(amount) {
if (amount > 1) amount = 1;
if (amount < 0) amount = 0;
if ($.browser.msie) {
amount = (parseFloat(amount) * 100);
this.css('filter', 'alpha(opacity='+amount+')');
} else {
this.css('opacity', amount);
this.css('-moz-opacity', amount);
}
return this;
}

EDIT: As Karl pointed out below, jQuery handles this natively. 8)

Comments

9 Responses to “Opacity Plugin for jQuery”

  1. Karl on June 22nd, 2007 8:32 pm

    Hi there,

    That’s a nifty little plugin. I’m pretty sure jQuery already handles opacity internally, though. You just need to do something like this, $('someElement').css('opacity',0.5), if you wanted to make an element 50% opacity, for example.

  2. Woodrow on June 22nd, 2007 10:21 pm

    For some reason I assumed that jQuery didn’t handle the differences between IE and standard opacity settings. Now that I’ve looked, I feel rather silly.

  3. Karl on June 23rd, 2007 7:28 am

    Heh, no worries, Woodrow. :)

    In case you’re interested, here are the lines from jquery.js (approx. 1574-1588) that deal with opacity:

    (edited by Woodrow: sorry Karl, your code wasn’t showing up properly, I had to clip it out. Anyone who is interested, here’s jQuery.js.)

  4. Karl on June 23rd, 2007 7:29 am

    oops. it didn’t quite wrap all of the code in pre/code tags. Sorry about that.

  5. Peter on January 19th, 2008 5:13 pm

    This post helped me! thanks. I assumed the same thing.

  6. Kris M. on February 14th, 2008 12:11 am

    Yup, this post helped, I assumed the same thing.

  7. Phil on July 22nd, 2008 12:57 pm

    ????? wtf!

  8. giacomo on October 25th, 2008 11:40 pm

    haha

  9. daveslow on November 26th, 2008 5:49 pm

    Quick note:
    jQuery doesn’t seem to handle this:
    $(’.someClass’).css( { opacity: ‘0.8′ });
    the same as this:
    $(’.someClass’).css( opacity, ‘0.8′ );
    I guess that’s good in a way, it keeps one method open for more control, but, it tripped me up as I was expecting otherwise.

Leave a Reply