Naveen DA
Naveen DA

Reputation: 4380

Get top,left position of the cursor in draftjs

How to get the cursor position(top, left) value in Draft.js. I have already seen this question, but it gives only the line number, but I want the top, left value.

Upvotes: 1

Views: 575

Answers (2)

chenjiahe
chenjiahe

Reputation: 29

editorState.getSelection().getAnchorOffset();

you can get the position of cursor like that

Upvotes: 1

MamorukunBE
MamorukunBE

Reputation: 120

This is working for my needs (NB: not tested on multi-platform/multi-browser, but at least it works great on Chrome/Firefox on Windows). The idea is to consider the caret as a mere window selection, and not as a draftjs selection. Hope it'll help.

function FindCaretPosition() {
    let selection = window.getSelection();
    let selectionRange = selection.getRangeAt(0).cloneRange();
    selectionRange.collapse(false);
    //-----
    let caretMarker = document.createElement("span");
    caretMarker.id = "__caret";
    selectionRange.insertNode(caretMarker);
    let caretPosition = document.querySelector("#__caret").getBoundingClientRect();
    //-----
    selectionRange.deleteContents();

    return { x: caretPosition.left, y: caretPosition.bottom }
}

Upvotes: 2

Related Questions