JSFiddle - React, Tailwind, and code Playground

by timdown

HTML

<div id="info">Caret position</div>
<div contenteditable="true" onkeyup="showCaretPos()" onmouseup="showCaretPos()">Type some stuff in here<div>

JavaScript

function getCaretClientPosition() {
    var x = 0, y = 0;
    var sel = window.getSelection();
    if (sel.rangeCount) {
        var range = sel.getRangeAt(0);
        if (range.getClientRects) {
            var rects = range.getClientRects();
            if (rects.length > 0) {
                x = rects[0].left;
                y = rects[0].top;
            }
        }
    }
    return { x: x, y: y };
}

function showCaretPos() {
    var pos = getCaretClientPosition();
    document.getElementById("info").innerHTML = "Caret position: " + pos.x + ", " + pos.y;
}