Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created March 21, 2015 19:56
Show Gist options
  • Save miguelmota/16fb3aa6d1650d1e065f to your computer and use it in GitHub Desktop.
Save miguelmota/16fb3aa6d1650d1e065f to your computer and use it in GitHub Desktop.
Get offset position of text in JavaScript
var characters = document.querySelector('.characters'); // div with text
var charactersText = characters.textContent;
var charAtIndex = 25;
var offsetPosition;
characters.textContent = '';
for (var i = 0; i < charactersText.length; i++) {
var textNode = document.createTextNode(charactersText[i]);
characters.appendChild(textNode);
if (i === charAtIndex) {
var range = document.createRange();
range.selectNodeContents(textNode);
var rects = range.getClientRects();
offsetPosition = {
left: rects[0].left,
top: rects[0].top
};
}
}
alert(JSON.stringify(offsetPosition, null, 2));
@yckart
Copy link

yckart commented May 18, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment