Wrote this for an upcoming upgrade to the Olam dictionary. Similar to autocomp.js (which was again written for Olam), but specifically for textareas to render a floating auto-suggestions widget. ~1200 bytes compressed, no dependencies.
TIL: Getting the x,y coords of the caret in a textarea relative to the page is surprisingly tricky.
- Have a hidden “shadow” div which the exact same styles as the textarea.
- Copy the contents of the textarea into the div.
- Insert a another DOM element in the shadow div relative to where the caret is in the textarea (obtained with selectionStart())
- Find the coords of this new element.
- Transpose those coords (relative) to visible textarea.