change element color based on background color in javascript

You can use the following code snippet to change the color of an element based on its background color:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #myDiv {
        width: 100px;
        height: 100px;
        background-color: yellow;
      }
    </style>
  </head>
  <body>
    <div id="myDiv">Hello World!</div>
    
    <script>
      // Get the background color of the element
      const myDiv = document.querySelector("#myDiv");
      const backgroundColor = window.getComputedStyle(myDiv).backgroundColor;
      
      // Determine the contrast color
      const isDark = determineIfDark(backgroundColor);
      const contrastColor = isDark ? "white" : "black";
      
      // Change the text color
      myDiv.style.color = contrastColor;
      
      // Function to determine if a color is dark
      function determineIfDark(color) {
        const rgb = color.match(/\d+/g);
        const brightness = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
        return brightness < 128;
      }
    </script>
  </body>
</html>

943 chars
37 lines

In this code, we get the current background color of the element using window.getComputedStyle(). We then use a function to determine if the background color is dark or light, and choose a contrasting color accordingly. Finally, we use myDiv.style.color to change the text color of the element.

gistlibby LogSnag