Skip to content

Instantly share code, notes, and snippets.

@ethanmay
Created April 19, 2023 18:33
Show Gist options
  • Save ethanmay/f960b28f5db0e668238a45557f31a090 to your computer and use it in GitHub Desktop.
Save ethanmay/f960b28f5db0e668238a45557f31a090 to your computer and use it in GitHub Desktop.
Luminance testing on scroll for a given x/y coordinate
<html>
<head>
<style>
body {
margin: 0;
padding: 0;
}
.nav {
position: fixed;
background: #FFF;
top: 10px;
left: 10px;
width: calc(100% - 20px);
}
.nav ul {
list-style: none;
margin: 0;
}
.nav li {
display: inline-block;
margin: 10px 20px;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="test-bg-color" style="background-color: rgba(0,0,0,0.7); height: 600px"></div>
<div class="test-bg-color" style="background-color: #fff; height: 600px"></div>
<div class="test-bg-color" style="background-color: #F4F3FA; height: 600px"></div>
<div class="test-bg-color" style="background-color: rgba(0,0,0,1); height: 600px"></div>
<div class="test-bg-color" style="background-color: #F4F3FA; height: 600px"></div>
<div class="test-bg-color" style="background-color: #fff; height: 600px"></div>
<div id="nav" class="nav">
<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
</ul>
</div>
<script>
function getRgbish(c) { // https://stackoverflow.com/questions/7543818/regex-javascript-to-match-both-rgb-and-rgba
var i = 0, itm,
M = c.replace(/ +/g, '').match(/(rgba?)|(\d+(\.\d+)?%?)|(\.\d+)/g);
if (M && M.length > 3) {
while (i < 3) {
itm = M[++i];
if (itm.indexOf('%') != -1) {
itm = Math.round(parseFloat(itm) * 2.55);
}
else itm = parseInt(itm);
if (itm < 0 || itm > 255) return NaN;
M[i] = itm;
}
if (c.indexOf('rgba') === 0) {
if (M[4] == undefined || M[4] < 0 || M[4] > 1) return NaN;
}
else if (M[4]) return NaN;
return M.slice(1);
}
return NaN;
}
const nav = document.getElementById('nav')
window.addEventListener('scroll', function () {
const eles = document.elementsFromPoint(nav.offsetLeft, nav.offsetTop).filter(ele => ele.classList.contains('test-bg-color'))
if (eles.length) {
const color = getRgbish(eles[0].style.backgroundColor)
const luminance = Math.sqrt(0.299 * Math.pow(color[0], 2) + 0.587 * Math.pow(color[1], 2) + 0.114 * Math.pow(color[2], 2))
if (luminance < 127.5) {
console.log('make nav light')
} else {
console.log('make nav dark')
}
} else {
console.log('unable to determine bg color - ensure a .test-bg-color element is present')
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment