How can I get the text that was clicked on in Javascript?

Posted by Jake on Stack Overflow See other posts from Stack Overflow or by Jake
Published on 2010-03-31T02:51:54Z Indexed on 2010/03/31 3:03 UTC
Read the original article Hit count: 273

Filed under:

Does anyone know if it is possible with javascript to to tell the position of a mouse click in some text? I know it's easy to get the x,y coordinates, but I'm wanting the position in the text.

For example if I clicked inside <p>foo bar</p> I want to be able to tell that the click was on/after the 5th character. Or that foo b is before the click and ar is after it.

By the way, I'm using jQuery too, I'm happy with pure JS and solutions that use jQ.

Thanks in advance.

© Stack Overflow or respective owner

Related posts about JavaScript