JSFiddle - React, Tailwind, and code Playground
by Jonathan Sampson
HTML
<div class="foo">
Hello, World. <span>Juice.</span>
<img src="http://placehold.it/50x50" /> Click me.
<p>I won't respond to clicks.</p>
I'll respond. Click me if you like.
</div>
CSS
.foo {
padding: 1em;
border: 1px solid red;
}
.foo img {
float: left;
margin: 0 1em 1em 0;
transform: translate(2em, 2em);
}
span, p {
color: #999;
}
JavaScript
var foo = document.querySelector( ".foo" );
foo.addEventListener( "click", function ( event ) {
if ( event.srcElement === this ) {
var clickedNode = textNodeFromPoint( this, event.clientX, event.clientY );
if ( clickedNode ) {
alert( "You clicked: " + clickedNode.nodeValue );
}
}
});
function textNodeFromPoint( element, x, y ) {
var node, nodes = element.childNodes, range = document.createRange();
for ( var i = 0; node = nodes[i], i < nodes.length; i++ ) {
if ( node.nodeType !== 3 ) continue;
range.selectNodeContents(node);
if ( isInside( x, y, range.getBoundingClientRect() ) ) {
return node;
}
}
return false;
}
function isInside ( x, y, rect ) {
return x >= rect.left && y >= rect.top
&& x <= rect.right && y <= rect.bottom;
}