Is there a way to modify the opacity value of a CSS background color with JavaScript?

Viewed 77

I have a css:

.class1 { background: #fff }

What I want is:

.class2 { background: rgba(255,0,0,0.5) };

Is there any way that I can use ONLY JavaScript to modify the background property of .class1, to make it has a opacity:.5 effect?

For example, I want something like this:

$('.class1').css('background-opacity', '.5');

Can anyone help?

Thanks

2 Answers

What you are looking for is probably a function that would return RGBA from HTML color...

Could be something like that:

var color = $('.class1').css("background-color"); // this will return RGB() color even if it was html color before
var opacity = 0.5;
color = color.toString().replace(/\)/g,"," + opacity + ")");
$('.class1').css("background-color",color);

Live Fiddle in here.

You can use CSS variable for this.

const div = document.querySelector("div");

div.addEventListener("click", () => {
  div.style.setProperty("--a", "0.5");
});
div {
  height: 100px;
  width: 100px;
  --a: 1;
  background: rgba(255, 0, 0, var(--a));
}
<div>
  Click for opacity.
</div>

Related