I'm finding tons of good, crossbrowser anwers on how to SET the cursor or caret position in a contentEditable DIV, but none on how to GET or find its position...
What I want to do is know the position of the caret within this div, on keyup.
So, when the user is typing text, I can at any point know its cursor's position within the div.
EDIT: I'm looking for the INDEX within the div contents (text), not the cursor coordinates.
<div id="contentBox" contentEditable="true"></div>
$('#contentbox').keyup(function() {
// ... ?
});
The following code assumes:
<div>
and no other nodeswhite-space
property set topre
Code:
A few wrinkles that I don't see being addressed in other answers:
Here's a way to get start and end positions as offsets to the element's textContent value:
This one works for me:
the calling line depends on event type, for key event use this:
for mouse event use this:
on these two cases I take care for break lines by adding the target index
Try this:
Caret.js Get caret postion and offset from text field
https://github.com/ichord/Caret.js
demo: http://ichord.github.com/Caret.js
Note: the range object its self can be stored in a variable, and can be re-selected at any time unless the contents of the contenteditable div change.
Reference for IE 8 and lower: http://msdn.microsoft.com/en-us/library/ms535872(VS.85).aspx
Reference for standards (all other) browsers: https://developer.mozilla.org/en/DOM/range (its the mozilla docs, but code works in chrome, safari, opera and ie9 too)