Background colour monitor - markhowellsmead/helpers GitHub Wiki

/**
 * Monitor the background colour behind the viewport point at 0 x 100px
 * and apply a CSS class to the documentElement if the background is dark.
 * This CSS class will then be used to adjust the text colour for better contrast.
 *
 * [email protected] 28th August 2024
 */

document.addEventListener('scroll', () => {
	const element = document.elementFromPoint(0, 100);

	if (element) {
		const style = getComputedStyle(element);
		const backgroundColor = style.backgroundColor;
		const isTransparent = backgroundColor === 'rgba(0, 0, 0, 0)';
		const rgbValues = backgroundColor.match(/\d+/g);

		if (!rgbValues || isTransparent) {
			document.documentElement.classList.remove('is--background--dark');
		} else {
			const [red, green, blue] = rgbValues.map(Number);

			// Calculate contrast (simple grayscale approximation)
			const contrast = (red * 0.299 + green * 0.587 + blue * 0.114) / 255;

			if (contrast < 0.5) {
				document.documentElement.classList.add('is--background--dark');
			} else {
				document.documentElement.classList.remove('is--background--dark');
			}
		}
	}
});