Search code examples
javascriptcsscolors

Toggle Color based on RGB or Hex values of DOM element


Why does the following code not toggle the element color when the button is clicked? My assumption is that the style.color is returning an object of sorts and not a string. What would be the best way to correct this issue?

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
asd=document.getElementById("demo")
if (asd.style.color!="rgb(255,0,0)")
asd.style.color="rgb(255,0,0)";
else
asd.style.color="rgb(0,0,0)";
}
</script>
</head> 
<body>

<h1>My First JavaScript</h1>

<p id="demo">
JavaScript can change the style of an HTML element.
</p>

<button type="button" onclick="myFunction()">Click Me!</button>

</body>
</html>

Solution

  • Browser vendors return various versions of the style.color value.

    From a quick test on this very page (which by pasting the code into the JavaScript console you can see for yourself):

    • IE8 returns "#888" for document.querySelectorAll('div[class="user-details"]')[0].currentStyle.color
    • Chrome and Firefox return "rgb(136, 136, 136)" for document.defaultView.getComputedStyle(document.getElementsByClassName('user-details')[0], null)['color']

    I'm fairly sure I've seen a previous version of one browser return "rgb(136,136,136)" (without spaces) before.

    One way to work around this inconsistency is to define the colors in CSS classes instead and toggle between the class names.

    A very simple demonstration of this would be the following code. However this is very simple as it would only work if the element has a single CSS class. You would need to write a utility function to check if an element has a class applied and functions to add and remove a single class from a list if your design needed multiple classes. These have been written many times before so there are plenty of examples (search for javascript hasclass addclass removeclass) or use an existing utility library.

    CSS

    .on {
        color:#f00;
    }
    
    .off {
        color:#000;
    }
    

    JavaScript

    function myFunction() {
        var e = document.getElementById("demo");
    
        e.className = e.className === 'on' ? e.className = 'off' : e.className = 'on';
    }
    

    HTML

    <h1>My First JavaScript</h1>
    
    <p id="demo" class="off">
    JavaScript can change the style of an HTML element.
    </p>
    
    <button type="button" onclick="myFunction()">Click Me!</button>