5

I'd like to take an existing background color of a div element and only adjust opacity... how would I do that?


Found very simple solution to my problem; requires jquery-color plugin but it's by far the best solution in my opinion:

$('#div').css('backgroundColor', $.Color({ alpha: value }));
tkane
  • 1,597
  • 3
  • 14
  • 18

4 Answers4

7

Opacity is tricky because there's still no cross-browser supported mechanism, even though its supposed to be in CSS3.

What you most likely want to do is change the background-color style's alpha channel. See: http://robertnyman.com/2010/01/11/css-background-transparency-without-affecting-child-elements-through-rgba-and-filters/


Someone has developed a JQuery plugin that does just what you want: http://archive.plugins.jquery.com/project/backOpacity

With this plugin, you can control just the "back opacity" without affecting child elements.

David Pfeffer
  • 38,869
  • 30
  • 127
  • 202
4

The query-color plugin is a nice solution, however I strongly believe you do not need to overload your app with unnecessary plugins for such an easy and simple task.

Here is another approach using strings:

var alpha = "0.8";

var oldBGColor = $('#div').css('backgroundColor');
// rgb(40,40,40)

var newBGColor = oldBGColor.replace('rgb','rgba').replace(')', ','+alpha+')'); 
// rgba(40,40,40,.8)

$('#div').css('backgroundColor', newBGColor);

Here is a jsFiddle example of how to use it.

I had a similar problem and it made the magic for me.

Community
  • 1
  • 1
Lior Elrom
  • 19,660
  • 16
  • 80
  • 92
0

if you want to go from opacity x.xxx to 1 you can do

var element = $("#id")
element.css('backgroundColor', element.css('backgroundColor').replace(/(\d\.?\d*)\s*\)/i, "1") )

to do the inverse just change 1 by the value you want.

Note your color need to have the "rgba(100, 100, 100, 0.85098)" format from the start

tolbard
  • 1,273
  • 15
  • 20
-1

Upload your background image or color in Photoshop and decrease the opaity there and save it as .jpeg image and then use it as the background in HTML.

Simple as that.... :D

  • JPEG isn't ([usually](http://stackoverflow.com/questions/2639866/jpeg-image-with-alpha-channel-on-website)) used with opacity. Using images is inefficient to start with, but for the specific purpose of having non-binary opacity, I'd say PNG is the way to go. – Joel Purra Feb 24 '13 at 16:52