2

I am trying to detect the position of text inside a HTML element (assume, <div> tag) (top, left, bottom and right coordinates) on the screen. I have tried offsetLeft, and offsetWidth. But, it doesn't help. Please help.

Thanks.

satish123
  • 541
  • 7
  • 25

1 Answers1

2

You were on the right track, not sure where you got lost but you can determine coordinates using the following:

Top:     node.offsetTop
Left:    node.offsetLeft
Bottom:  (node.offsetTop + node.offsetHeight)
Right:   (node.offsetLeft + node.offsetWidth)

https://jsfiddle.net/p56xgpmb/

Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • Thanks @Rob for your reply. But, what I understand is that, these are coordinates for the `
    ` element. Text coordinates, width & height may vary. Right? How to find those?
    – satish123 May 05 '15 at 19:42
  • These are the coordinates for the `p` tag, not the `div`. Text nodes do not have the same methods as element nodes so you cannot use the `offset` methods. Text Nodes cannot be targeted with CSS though, so you can safely assume the parent element's position is representative of the text node's position. – Rob M. May 05 '15 at 19:49
  • Ok. Still if you try on the link you gave to me on jsfiddle. Even deleting some text or increasing the text, the Right coordinate doesn't change – satish123 May 05 '15 at 20:05
  • You can adjust the css of the containing element to not be full-width as seen here: http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript. Then the coordinates will be accurate to the text width/height. – Rob M. May 05 '15 at 20:21
  • If the parent has other inline child nodes there will be multiple textNode which could be anywhere. – SuperUberDuper Aug 26 '16 at 16:57