Created
March 21, 2015 19:56
-
-
Save miguelmota/16fb3aa6d1650d1e065f to your computer and use it in GitHub Desktop.
Get offset position of text in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/miguelmota/textnode-offset ;)