3

In my HTML, I have a paragraph that contains a lot of text.

<p>
    ... abc ...
    ... def ...
    ... ghi ...
    ... jkl ...
    ... mno ...
</p>

What I want now is to be able to get the position in X and Y coordinates of h in the third line. I have searched all over the web, but I can't find it. How would I do this?

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
Nicky Smits
  • 2,980
  • 4
  • 20
  • 27
  • I don't think you can do that unless you wrap the h in a specifig html tag. – Romain Braun Mar 20 '14 at 16:14
  • surely this would depend on the paragraph width? – Harry Mar 20 '14 at 16:15
  • How do you want to get the coordinates? With javascript? – Harry Mar 20 '14 at 16:16
  • Yeah. I was afraid for that. I actually want to use this for an extension, so changing the DOM is not prefered. – Nicky Smits Mar 20 '14 at 16:16
  • I want the coordinats with Javascript yes. And this has nothing to do with the width. I want to automatically scroll with 100words/minute. And i do not want to use line-height to calculate the distance, since there may be inline images and stuff. It's for a chrome extension. – Nicky Smits Mar 20 '14 at 16:17
  • Read the answers of this thread : http://stackoverflow.com/questions/5143534/get-the-position-of-text-within-an-element – Romain Braun Mar 20 '14 at 16:18
  • How can i safely pack a word in the paragraph in span tags? I do not want the text to 'flicker' because it is fully reloaded. I could indeed pack it, get the position, and unpack it, like the packing never happened. – Nicky Smits Mar 20 '14 at 16:20
  • I don't see why it would flicker ? – Romain Braun Mar 20 '14 at 16:24
  • 1
    Well.. if i would change innerHTML of p from '>a b c<' to '>a b c<'. The innerHTML would probably first be emptied,a dn then filled with its new content. And i can't get the INNERHTML if there are div nodes inside.. – Nicky Smits Mar 20 '14 at 16:29
  • Of course you can. And I'm sure the flickering wouldn't be noticeable. It's worth trying. – Romain Braun Mar 20 '14 at 16:32

1 Answers1

5

Create a Range containing just the character in question (up to you how you do this; I'd suggest something like searching through all the text nodes in your paragraph until you find the one you want) and call its getBoundingClientRect() method.

Tim Down
  • 318,141
  • 75
  • 454
  • 536