reactjsdraftjs

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.


Solution

  • 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 }
    }