Use elementFromPoint to compare overlapping elements
by Gerald Fullam
March 19, 2015
HTML
<div id="box1"></div>
<div id="box2">
<p id="myText">Treasure.</p>
</div>
<button id="myButton" type="button">Find sunken treasure</button>
<hr />
<p>Note: Change the position of #myText in the CSS and click 'Run' to see how the script responds to the text when it is not over a same-colored background.</p>
CSS
#box1 {
width: 100%;
height: 100px;
background-color: lightseagreen;
}
#box2 {
width: 100%;
height: 100px;
background-color: sandybrown;
}
#myText {
font-size: 32px;
color: lightseagreen;
position: relative;
top: -20px; /* Change vertical position of text here. */
}
p {
margin: 0;
text-align: center;
}
JavaScript
var myButton = document.getElementById('myButton');
myButton.onclick = findHiddenText;
function findHiddenText() {
var textElem = document.getElementById('myText'),
textOffset = textElem.getBoundingClientRect(),
textColor = getStyle(textElem, 'color'),
textZindex = getStyle(textElem, 'zIndex');
textElem.style.zIndex = '-1';
var bgElem = document.elementFromPoint(textOffset.left, textOffset.top),
bgColor = getStyle(bgElem, 'backgroundColor');
if (textColor === bgColor) {
var msgElem = document.createElement('p'),
msgText = document.createTextNode('There be hidden treasure in the sea.');
msgElem.appendChild(msgText);
document.getElementById('box2').appendChild(msgElem);
textElem.style.textShadow = '0 1px 1px #000';
};
textElem.style.zIndex = textZindex;
}
function getStyle(elem, prop) {
if (elem.currentStyle) {
return elem.currentStyle[prop];
}
return document.defaultView.getComputedStyle(elem, null)[prop];
}