6

I'm new to jquery and i'm a bit surprised: when I write

$('#selected-color').css('background-color', 'rgba(0,0,0,1)');

My final style of #selected-color ends up being rgb(0,0,0). This makes a big difference when I get the background-color back and try applying a regexp on it, expecting getting a rgba string.

So the question is Is Jquery applying automatic conversion on rgba values when alpha is set to 1 ? I had the same result with a=1.0 but I get a RGBA with a=0.99. I had no success indications on this in the jquery documentation

Clement
  • 281
  • 1
  • 2
  • 8
  • 1
    Not jQuery's fault; I'm getting the same result when I use vanilla JavaScript. –  Aug 01 '18 at 08:37
  • with `a = 1` not make any sense that why its get replaced by javascript. any value which affect the transparency will work fine – Anand Singh Aug 01 '18 at 08:46

1 Answers1

0

This is not a jQuery feature. All colour expressions are evaluated into rgb expressions when alpha = 1 and into rgba expressions when alpha < 1.

From MDN Documentation:

Computed value: If the value is translucent, the computed value will be the rgba() corresponding one. If it isn't, it will be the rgb() corresponding one. The transparent keyword maps to rgba(0,0,0,0).

In the CSS3 SPEC:

Computed value:

  • The computed value for basic color keywords, RGB hex values and extended color keywords is the equivalent triplet of numerical RGB values, e.g. six digit hex value or rgb(...) functional value, with an alpha value of 1.
  • The computed value of the keyword ‘transparent’ is the quadruplet of all zero numerical RGBA values, e.g. rgba(0,0,0,0).
  • For all other values, the computed value is the specified value.

Example:

var
  foo = document.getElementById("foo"),
  getBGColor = function () {
    return getComputedStyle(foo, null).backgroundColor;
  };

/* Setting the background with an alpha value of 1. */
foo.style.backgroundColor = "rgba(0, 0, 0, 1)";
console.log("alpha = 1: ", getBGColor());

/* Setting the background with a hex number. */
foo.style.backgroundColor = "#000";
console.log("alpha = 1: ", getBGColor());

/* Setting the background with a hsl expression. */
foo.style.backgroundColor = "hsl(120, 100%, 25%)";
console.log("alpha = 1: ", getBGColor());

/* Setting the background with an alpha value less than 1. */
foo.style.backgroundColor = "rgba(0, 0, 0, .5)";
console.log("alpha < 1: ", getBGColor());

/* Setting the background with a hsla expression. */
foo.style.backgroundColor = "hsla(120, 100%, 25%, .5)";
console.log("alpha < 1: ", getBGColor());
<div id = "foo"></div>
Angel Politis
  • 10,955
  • 14
  • 48
  • 66