Get char index when clicking in a div
by Simon Hi
HTML
<!-- zero-width space characters (U+200B) were inserted between each char of the div below -->
<div onclick='magic(this)'>This is a simple example.</div>
<p>Click on a char of the above sentence to get its index!</p>
<p>Note: index starts at 0!</p>
CSS
div {
font-size: 3rem;
}
JavaScript
function magic(e) {
var s, p, c;
s = e.innerHTML;
p = window.getSelection().focusOffset;
c = s.charAt((p >> 1) << 1);
alert("index:" + (p >> 1) + " char: '" + c + "'");
}