How to Calculate the Opacity of an 8-Digit Hexadecimal Color Using JavaScript?

Using JavaScript, you can calculate the opacity percentage of an 8-digit hexadecimal color code in the following way:

  1. If non-8-digit color code, then return 100 (i.e. fully opaque);
  2. If 8-digit color code, then extract the last two digits (i.e. alpha channel value) from it, and;
  3. Calculate the opacity (in percent) for the extracted last two digits of the 8-digit color code.

For example, you can implement this in the following way:

const calcHexOpacity = (hexValue) => {
    // 1: if not 8-digit color code, return `100`
    if (hexValue.length < 8) {
        return 100;

    // 2: extract alpha channel value (last two digits)
    const alpha = parseInt(hexValue.substring(6, 8), 16);
    // 3: calculate opacity in percent
    const opacity = Math.round(alpha / 255 * 100);

    return Math.round(alpha / 255 * 100);

console.log(calcHexOpacity('0000ff00')); // 0
// ...
console.log(calcHexOpacity('0000ff40')); // 25
// ...
console.log(calcHexOpacity('0000ff80')); // 50
// ...
console.log(calcHexOpacity('0000ffbf')); // 75
// ...
console.log(calcHexOpacity('0000ffff')); // 100

This code works as follows:

  1. The code first checks if the hexadecimal color code has 8 digits. If it does not, it means that there is no alpha channel value in the code and the opacity percentage is assumed to be 100%. Therefore, the function returns 100.
  2. If the color code has 8 digits, the alpha channel value is extracted from the last two digits of the code.
  3. To calculate the opacity percentage, the alpha channel value is first converted from an integer between 0 (fully transparent) and 255 (fully opaque) to a decimal value between 0 and 1 by dividing it by 255. The resulting decimal value is then multiplied by 100 to get the opacity percentage, which is represented as a number between 0 and 100.
  4. The opacity percentage is then rounded to the nearest integer using the Math.round() function to provide a whole number value for the opacity percentage.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.