I am trying to track and restore the caret position inside nested contentEditable div my code will be like.
<div id="parentDiv" contentEditable={"true"}>
<div id="chip-1" styles={color: "red",border: "1px solid #999",border-radius: "10px",margin-right: "5px",padding: "3px"}>
TotalCurrentRatio
</div>
<div id="chip-2" styles={color: "red", margin-right: "5px",padding: "3px"}>
/
</div>
<div id="chip-3" styles={color: "red",border: "1px solid #999",border-radius: "10px",margin-right: "5px",padding: "3px"}>
NetAsset
</div>
</div>
<button id="button" onClick={setCaret}>
GetCaret
</button>
<button id="FoucsButton" onClick={focusEnd}>
setCaret
</button>
I am trying to make two functions
GetCaret: which save current postion of caret in a variable.
SetCaret: which sets the position of character based on postion returned by the GetCaret I had tried many solutions like
const GetCaret= (
containerEl: EventTarget & HTMLDivElement
) => {
var range = window.getSelection()!.getRangeAt(0);
var preSelectionRange = range.cloneRange();
preSelectionRange.selectNodeContents(containerEl);
preSelectionRange.setEnd(range.startContainer, range.startOffset);
var start = preSelectionRange.toString().length;
return {
start: start,
end: start + range.toString().length,
};
};
2.SetCaret
const setCaret = (
caretPosition: {
start: number;
end: number;
}
) => {
var el = document.getElementById("parentDiv");
var range = document.createRange();
var sel = window.getSelection();
if (el !== null && sel !== null && el.innerText.length > 0) {
range.setStart(el, 4314);
range.collapse(true);
console.log("setCaret ", caretPosition.end);
sel.removeAllRanges();
sel.addRange(range);
el.focus();
}
return;
};
But it is not working for nested contentEditable div(as shown above)
screenshot of my component:
