JCursorPos is a lightweight (3kb gzip), cross browser plugin to get the cursor x / y and top / left coordinates in a textarea or input element. Once initialized, the cursor x / y position will be updated on the element's data-*
attribute, and optionally passed to a callback function.
To use, simply include jquery.jcursorpos.js
and do the following:
$('textarea').jCursorPos({
onChange: function(cursor) {
// the source element where the cursor is active
var el = $(this);
// the x/y of the cursor relative to the document
console.log(cursor.offset.left);
console.log(cursor.offset.top);
// the x/y of the cursor relative to the textarea
console.log(cursor.position.left);
console.log(cursor.position.top);
}
});
The cursor position relative to the window will be returned, as well as the position of the cursor relative to the inside of the textarea or input element.
An onChange
callback is fired everytime the cursor moves, passing a cursor
object as a function parameter.
The cursor
object contains the following properties:
offset | top | Y coordinate of the cursor from the document window |
left | X coordinate of the cursor from the document window | |
position | top | Y coordinate of the cursor from the source element |
left | X coordinate of the cursor from the source element |
Copyright (c) 2013 David Shariff Licensed under the MIT license.