0

When assigning a hsl color using Javascript, it doesn't apply it as an HSL color, but rather converts it to RGB.

document.body.style.backgroundColor = "hsl(0,100%,50%)"
document.body.style.backgroundColor; // "rgb(255, 0, 0)"

I was hoping to assign an HSL color, then modify the saturation and brightness after the fact, but I can't do that easily since it gets converted to RGB.

Is there a way to keep it from converting to RGB, or is converting it back to HSL manually necessary?

Eastonium
  • 313
  • 2
  • 6
  • you will need to either 1) keep the HSL value in a variable, or 2) convert the RGB value to HSL: [see this](http://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion) – Ryan Wheale Aug 01 '16 at 18:37
  • 1
    For what purpose do you want to keep the HSL colors? Screens can only display RGB, so visually, there's no difference unless you're trying to create printable documents, which would require CMYK colors - I've only seen those in the CSS4 draft. – TheThirdMan Aug 01 '16 at 18:40
  • Would this be helpful? http://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion – Asons Aug 01 '16 at 18:43
  • @TheThirdMan I was hoping to keep the HSL format so I could easily change the saturation and lightness/brightness after the fact for a dynamic webpage. – Eastonium Aug 01 '16 at 18:47
  • I see... though within CSS, a HSL color code should actually be a single value of `hsl(0,100%,50%)`, for example, so there's no easy way to access it after the fact. Maybe you should go with variables instead? You could also set attributes to the element you want to apply the background color to, and re-apply the CSS whenever you change those attributes. – TheThirdMan Aug 01 '16 at 18:58
  • @TheThirdMan I think an attribute is the way to go in my instance, which is for an svg element. svg elements accept either a style or attribute "fill" which specifies the color. Thank you for that suggestion! – Eastonium Aug 01 '16 at 19:54
  • In case of an SVG, attributes are indeed what I would recommend. Please consider posting your solution as an answer and accept it so that the question will be removed from the unanswered queue, and others can more easily find the solution to the problem if they stumble upon this page! – TheThirdMan Aug 01 '16 at 20:30
  • Asked similarly a year ago, with no responses: http://stackoverflow.com/questions/30440423/get-hsl-color-with-javascript – jabbett Aug 01 '16 at 21:13

1 Answers1

0

For SVG elements, you can use an attribute instead of a style for the "fill" color, and it will keep the HSL format.

As for elements in general, storing the HSL value as a variable or attribute to pull from when modifying/reapplying the color may be the simplest solution.

Eastonium
  • 313
  • 2
  • 6