2

I wanted to add some spans dynamically with hsl background-color applied to style attribute, like this:

<span style="background-color: hsl(190, 75%, 43%)"></span>

Here is my jQuery doing this:

var hues = [ 172, 178, 184, 190, 196, 202, 208 ];

$.each(hues, function(index, backgroundHue) {
    var newSpan = $('<span></span>');
    newSpan.css('background-color', 'hsl('+backgroundHue+', 75%, 43%)');
    someBlock.append(newSpan);
});

But as a result i got span with rgb() background color (auto-converted from hsl()):

<span style="background-color: rgb(27, 165, 192);"></span>

Here is a fiddle: https://jsfiddle.net/pbjcvwdh/5/

Can anyone explain why is this and is there any way to avoid this auto-conversion? If I apply background-color statically in html it doesn't change to rgb().

DamianoPantani
  • 1,168
  • 2
  • 13
  • 23

3 Answers3

2

jQuery has nothing to do with this behaviour - it's simply because browsers render the value in RGB format. You can't change it unfortunately. If you want to get the value in HSL format you need to convert it back from RGB. This question can help you with that, if required.

To prove the above, here's a native JS implementation that exhibits the same behaviour:

[172, 178, 184, 190, 196, 202, 208].forEach(function(backgroundHue) {
  var span = document.createElement('span');
  span.style.backgroundColor = 'hsl(' + backgroundHue + ', 75%, 43%)';
  document.querySelector('.add-em-here').appendChild(span);
});
.add-em-here span {
  display: inline-block;
  height: 40px;
  width: 40px;
  border: 2px solid white;
  margin-left: 6px;
}
<div class="add-em-here">
  <!-- Added statically - stays with hsl() -->
  <span style="background-color: hsl(60, 75%, 43%)"></span>

  <!-- Added dynamically - auto-replaced with rgb() -->
</div>
Community
  • 1
  • 1
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

jQuery doesn't manipulate the source HTML received by the server. It manipulates the in-memory representation of the document tree. As such, there's no HTML at all (or CSS in this case) to be shown.

What happens is that whatever tool you use to debug your code has to implement a representation of those in-memory values. HTML and CSS are common an obvious choices but both of them need to be recreated for you and here's where different implementations will possibly differ. For instance, Firebug's Style pane makes it configurable:

Let's change it to HSL

Voilá!

Now HEX...

(My Firefox is localised but I hope you get the idea.)

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
1

If you want it to stay in HSL, use .attr() instead of .css():

newSpan.attr('style', 'background-color:hsl('+backgroundHue+', 75%, 43%)');

In doing so, the page will render with HSL instead of RGB.