Home

Awesome

Textarea Caret Position

Get the top and left coordinates of the caret in a <textarea> or <input type="text">, in pixels. Useful for textarea autocompletes like GitHub or Twitter, or for single-line autocompletes like the name drop-down in Twitter or Facebook's search or the company dropdown on Google Finance.

How it's done: a faux <div> is created off-screen and styled exactly like the textarea or input. Then, the text of the element 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 (because wrapping can push the currently typed word onto the next line). The same is done for the input to simplify the code, though it makes no difference. Finally, the span's offset within the textarea or input is returned.

Demo

Check out the JSFiddle or the test.html.

Features

Example

var getCaretCoordinates = require('textarea-caret');

document.querySelector('textarea').addEventListener('input', function () {
  var caret = getCaretCoordinates(this, this.selectionEnd);
  console.log('(top, left, height) = (%s, %s, %s)', caret.top, caret.left, caret.height);
})

API

getCaretCoordinates(element, position)

The function returns a caret coordinates object of the form {top: , left: , height: }, where:

Known issues

Dependencies

None.

TODO

Implementation notes

For the same textarea of 25 rows and 40 columns, Chrome 33, Firefox 27 and IE9 returned completely different values for computed.width, textarea.offsetWidth, and textarea.clientWidth. Here, computed is getComputedStyle(textarea):

Chrome 33

IE 9: scrollbar looks 16px, the text itself in the text area is 224px wide

Firefox 27

Contributors