HomeJavascriptColor Contrast Checker | Javascript Project

Color Contrast Checker | Javascript Project

Welcome to yet another exciting tutorial by Coding Artist. Building projects is one of the best ways to learn Javascript. So in today’s tutorial let us expand our javascript knowledge with a fun and easy-to-build project called ‘Color Contrast Checker’. To build this project we need HTML, CSS, and Javascript.

Video Tutorial:

Welcome to yet another exciting tutorial by Coding Artist. Building projects is one of the best ways to learn Javascript. So in today’s tutorial let us expand our javascript knowledge with a fun and easy-to-build project called ‘Color Contrast Checker’. To build this project we need HTML, CSS, and Javascript.

Project Folder Structure:

Let’s build the project folder structure before we begin writing the code. We create a project folder called ‘Color Contrast Checker’. Inside this folder, we have index.html, style.css, and script.js.

HTML:

We begin with the HTML Code. First, create a file called – ‘index.html’. Copy the code below and paste it into your HTML file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Color Contrast Checker</title>
    <!-- Google Fonts -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <div class="input-colors">
        <div class="color-container">
          <label for="text-color">Text Color:</label>
          <input type="color" id="text-color" value="#000000" />
        </div>
        <div class="color-container">
          <label for="bg-color">Background Color:</label>
          <input type="color" id="bg-color" value="#3277f6" />
        </div>
      </div>
      <div class="result">
        <div id="preview">
          Lorem, ipsum dolor sit amet consectetur adipisicing elit. Voluptas,
          ut.
        </div>
        <p id="contrast">1</p>
        <p id="rating">Demo Text</p>
      </div>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Next, we style our list using CSS. For this copy, the code provided to you below and paste it into your stylesheet.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #3277f6;
}
.container {
  position: absolute;
  width: 90%;
  max-width: 37.5em;
  background-color: #ffffff;
  border-radius: 0.8em;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 3em;
}
.input-colors {
  display: flex;
  justify-content: space-between;
}
.color-container {
  display: flex;
  flex-direction: column;
}
input[type="color"] {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  background-color: transparent;
  width: 7em;
  height: 7em;
  border: none;
}
input[type="color"]::-webkit-color-swatch {
  border-radius: 0.5em;
  border: 0.5em solid #c7c7c7;
}
input[type="color"]:-moz-color-swatch {
  border-radius: 0.5em;
  border: 0.5em solid #c7c7c7;
}
.result {
  margin-top: 1em;
}
#preview {
  padding: 1.5em;
  line-height: 1.8em;
  text-align: center;
  border-radius: 0.5em;
}
#contrast {
  text-align: center;
  font-size: 3em;
  margin-top: 1em;
}
#rating {
  text-align: center;
  padding: 0.8em 0;
  border-radius: 0.5em;
}
@media screen and (max-width: 600px) {
  .container {
    font-size: 0.9em;
  }
  input[type="color"] {
    font-size: 0.8em;
  }
}

Javascript:

The parts involved in creating this are as follows:

  • Create initial references and declare variables.
  • When the user changes the background color, or text color or when the window loads we call the ‘contrastChecker’ function.
  • The ‘contrastChecker’ function calculates the contrast ratio between the text color and background color, updates the contrast ratio and rating elements with the calculated values, and updates the preview element with the selected text color and background color.
  • The ‘getRelativeLuminance’ function calculates the relative luminance of a color based on its RGB values.
  • The ‘calculateContrastRatio’ function calculates the contrast ratio between two colors based on their relative luminance values.
  • The ‘calcRating’ function assigns a rating to the contrast ratio based on predefined thresholds and sets the background color of a rating element accordingly.
  • The ‘hexToRGB’ function converts a hex color value to an RGB array.
//Initial References
let textColor = document.getElementById("text-color");
let bgColor = document.getElementById("bg-color");
let previewText = document.getElementById("preview");
let contrastRef = document.getElementById("contrast");
let rating = document.getElementById("rating");

//Function to convert hex value to RGB array
function hexToRGB(colorValue) {
  const red = parseInt(colorValue.substring(1, 3), 16);
  const green = parseInt(colorValue.substring(3, 5), 16);
  const blue = parseInt(colorValue.substring(5, 7), 16);
  return [red, green, blue];
}

let getRelativeLuminance = (color) => {
  const sRGB = color.map((val) => {
    const s = val / 255;
    return s < 0.03928 ? s / 12 / 92 : Math.pow((s + 0.055) / 1.055, 2.4);
  });
  return 0.2126 * sRGB[0] + 0.7152 * sRGB[1] + 0.0722 * sRGB[2];
};

let calculateContrastRatio = (color1, color2) => {
  const luminance1 = getRelativeLuminance(color1);
  const luminance2 = getRelativeLuminance(color2);

  const light = Math.max(luminance1, luminance2);
  const dark = Math.min(luminance1, luminance2);
  const contrast = (light + 0.05) / (dark + 0.05);
  return contrast;
};

let calcRating = (contrastVal) => {
  if (contrastVal > 12) {
    rating.style.backgroundColor = "#69eb67";
    return "Super";
  } else if (contrastVal > 7) {
    rating.style.backgroundColor = "#b7ea84";
    return "Very Good";
  } else if (contrastVal > 5) {
    rating.style.backgroundColor = "#f7d658";
    return "Good";
  } else if (contrastVal > 3) {
    rating.style.backgroundColor = "#f17a55";
    return "Poor";
  } else {
    rating.style.backgroundColor = "#f24646";
    return "Very Poor";
  }
};

let contrastChecker = () => {
  let textColorValue = textColor.value;
  let textColorRGBArray = hexToRGB(textColorValue);

  let bgColorValue = bgColor.value;
  let bgColorRGBArray = hexToRGB(bgColorValue);

  //   console.log(textColorValue, textColorRGBArray);
  //   console.log(bgColorValue, bgColorRGBArray);

  const contrast = calculateContrastRatio(textColorRGBArray, bgColorRGBArray);

  contrastRef.innerText = contrast.toFixed(2);
  rating.innerText = calcRating(contrast);
  previewText.style.cssText = `
  background-color: ${bgColorValue};
  color: ${textColorValue}
  `;
};

textColor.addEventListener("input", contrastChecker);
bgColor.addEventListener("input", contrastChecker);
window.addEventListener("load", contrastChecker);

Go ahead and customize the project the way you like. If you have any queries, suggestions, or feedback comment below. Download the source code by clicking the ‘Download Code’ button below.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

thirteen + nineteen =

Most Popular