I am using jQuery and trying to find a cross browser way to get the pixel coordinates of the caret in <textarea>
s and input
boxes such that I can place an absolutely positioned div around this location.
Is there some jQuery plugin? Or JavaScript snippet to do just that?
I've looked for a textarea caret coordinates plugin for meteor-autocomplete, so I've evaluated all the 8 plugins on GitHub. The winner is, by far, textarea-caret-position from Component.
A mirror <div>
is created off-screen and styled exactly like the <textarea>
. Then, the text of the textarea up to the caret is copied into the div and a <span>
is inserted right after it. Then, the text content of the span is set to the remainder of the text in the textarea, in order to faithfully reproduce the wrapping in the faux div.
This is the only method guaranteed to handle all the edge cases pertaining to wrapping long lines. It's also used by GitHub to determine the position of its @ user dropdown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With