Search code examples
javascriptcssbrowserrgbhsl

How to stop Javascript code to convert hsl to rgb automatically


I have this code where I assign a color to an object and then I use a conditional to check if this item have already been selected or not. However the conditional doesn't work because the javascript (or the browser) converts the hsl to rgb which prevents any match from happening. I wonder if there is a way to stop this behaviour from JS (or the browser) and if not, why does it happen?

function selecionarNota() {

    if (this.style.backgroundColor == 'hsl(25, 97%, 53%)') { 
        for (let i = 0; i < numAvaliacao.length; i++) {
            numAvaliacao[i].style.backgroundColor = 'hsl(213, 19%, 21%)';
            numAvaliacao[i].style.color = 'hsl(217, 12%, 63%)';
        }

    } else {

        for (let i = 0; i < numAvaliacao.length; i++) {
            numAvaliacao[i].style.backgroundColor = 'hsl(213, 19%, 21%)';
            numAvaliacao[i].style.color = 'hsl(217, 12%, 63%)';
        }

        this.style.backgroundColor = 'hsl(25, 97%, 53%)';
        this.style.color = 'white';

    }
}

I do realize that I can work this problem by using rgb in the code instead. But I would really like to understand why does that happen.


Solution

  • It happens because it's the standard for browsers.

    I recommend creating css classes with these colors and apply those classes in javascript. You can then use element.classList.contains(class) in your conditionals.