Reputation: 149
I have a div
<div id="user_status" class="status expanddiv" onkeyup="username_Search('New','user_status');" contenteditable="true" data-text="What's on your mind?...">
Some Text will goes Here.
</div>
when username_Search function call, its through cursor at 0 postion. while i need to stay cursor at its actual postion. i can get cursor postion before call this function. but not able to set.
Does ant one have solution for this?
Upvotes: 4
Views: 121
Reputation: 1714
If you are using Chrome or Firefox then the below code will works well to accomplish the task. This code not tested in IE or Safari.
The setCaretPosition function is what you want I think
function getCaretPosition(editableDiv) {
var caretPos = 0, containerEl = null, sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
if (range.commonAncestorContainer.parentNode == editableDiv) {
caretPos = range.endOffset;
}
}
}
return caretPos;
}
function setCaretPosition(ctrl, pos) {
if (window.getSelection) {
pos = (ctrl.textContent.length > pos ? pos : ctrl.textContent.length);
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(ctrl.childNodes[0]);
range.endOffset = pos;
selection.removeAllRanges();
selection.addRange(range);
selection.collapse(ctrl.childNodes[0], pos);
}
}
function username_Search(st,str)
{
var ctl = document.getElementById('user_status');
var pos = getCaretPosition(ctl);
document.getElementById("user_status").textContent
= "dsdssadsadasdffstjdyjdrtyurtystseryds";
setCaretPosition(ctl,pos);
}
<div id="user_status" class="status expanddiv" onkeyup="username_Search('New','user_status');" contenteditable="true" data-text="What's on your mind?...">
Some Text will goes Here.
</div>
Upvotes: 1