ā†

Push Contrast Ratio to GTM

2 min read
2021-10-17

For UX and Accessibility (a11y) purpose, between background and foreground text(s), which is the Color Contrast, should be great enough to ensure legibility.

In this case, we'll use the Web AIM's contrast checker API for measure programmatically user's browser text-foreground contrast ratio, and push to Google Tag Manager through dataLayer

Before starting, we should create variable for colors with Window.getComputedStyle()

More information about Window.getComputedStyle()

List the elements on your website whose Color Contrast values you want to measure for Web Content Accessibility Guidelines (WCAG).

var bodyColor = getComputedStyle(document.querySelector("body")).color; var textColor = getComputedStyle(document.querySelector("h1")).color;

This should be return like this:

rgb(0, 0, 0) rgb(52, 247, 100)

And then we should convert this RGB values to HEX color.

var bodyColorToHex = bodyColor .slice(4, -1) .split(",") .map((x) => (+x).toString(16).padStart(2, 0)) .join("");

This time, we can use the Web AIM API as dynamically.

fetch( `https://webaim.org/resources/contrastchecker/?fcolor=${fColor}&bcolor=${bColor}&api` ) .then((response) => response.json())

And finally, we can push the all JSON resonses to GTM through dataLayer

.then((data) => {
    console.log(data), (window.dataLayer = window.dataLayer || []);
    window.dataLayer.push({
      ratio: data.ratio,
      AA: data.AA,
      AALarge: data.AALarge,
      AAA: data.AAA,
      AAALarge: data.AAALarge
    });
  });

Be sure the current dataLayer object is return for responsed contrast values:

Contrast Ratio Data Layer Object

Your last script should be look like this šŸ‘‡

var bodyColor = getComputedStyle(document.querySelector("body")).color;
var textColor = getComputedStyle(document.querySelector("h1")).color;

var bodyColorToHex = bodyColor
  .slice(4, -1)
  .split(",")
  .map((x) => (+x).toString(16).padStart(2, 0))
  .join("");
var textColorToHex = textColor
  .slice(4, -1)
  .split(",")
  .map((x) => (+x).toString(16).padStart(2, 0))
  .join("");

var fColor = bodyColorToHex;
var bColor = textColorToHex;
fetch(
  `https://webaim.org/resources/contrastchecker/?fcolor=${fColor}&bcolor=${bColor}&api`
)
  .then((response) => response.json())
  .then((data) => {
    console.log(data), (window.dataLayer = window.dataLayer || []);
    window.dataLayer.push({
      ratio: data.ratio,
      AA: data.AA,
      AALarge: data.AALarge,
      AAA: data.AAA,
      AAALarge: data.AAALarge
    });
    console.log(dataLayer);
  });

I highly recommended for this article to understanding how calculated color and contrast ratio for WCAG criteria.

šŸ”— https://webaim.org/articles/contrast/