I have a standard content editable div:
<div id="profileBody" class="customInputDiv" contentEditable='true' autocomplete="off"></div>
Basically I want to detect whereabouts the cursor is on a certain event (preferably code that works onclick
, keydown
or on button).
Something like this:
onkeydown
- save caret position within the div, then set caret position.
This sounds slightly silly, but is required because on certain events I will be changing the content slightly and when doing the cursor position changes which is very annoying.
I hate doing questions without examples of what I've tried but if you read previous questions I've always provide what I've tried very detailed, just hit a dead end here!
function setCaret() {
var el = document.getElementById("editable");
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el.childNodes[2], 5);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
el.focus();
}
Maybe a good way of parsing the data from window.getSelection();
?
Found: http://jsfiddle.net/s5xAr/3/ But i dont want the -- just want it to get the caret position using a function and set it e.g.
getCaretPOS();
//do something
setCaretPOS();
This code will set it but getting it seems to be the issue..