JSFiddle - React, Tailwind, and code Playground

by tnhu

HTML

<textarea id="t"></textarea>
<br>
<span id="tooltip" style="background:yellow"></span>

<span id="caret"/>

CSS

body {
  position: relative;
}

#caret {
  display: inline-block;
  position: absolute;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: rgba(255, 0, 0, .4);
}

textarea {
    height: 80px;
    line-height: 12px;
    overflow-y:scroll;
}
span {
 position: absolute;
}
}

JavaScript

$(document).ready(function () {
		var $caret = document.getElementById('caret')

    var cols = document.getElementById('t').cols;
    var width = document.getElementById('t').clientWidth;
    var height = $('textarea').css('line-height');
    var pos = $('textarea').position();
    $('#t').on('keyup', function () {
        el = document.getElementById("t");
        if (el.selectionStart) { 
            selection = el.selectionStart; 
          } else if (document.selection) { 
            el.focus(); 
            var r = document.selection.createRange(); 
            if (r == null) { 
               selection = 0; 
            } 
            var re = el.createTextRange(), 
            rc = re.duplicate(); 
            re.moveToBookmark(r.getBookmark()); 
            rc.setEndPoint('EndToStart', re); 
            selection = rc.text.length; 
          } else { selection = 0 }
        var row = Math.floor((selection-1) / cols);
        var col = (selection - (row * cols));
        var x = Math.floor((col*(width/cols)));
        var y = (parseInt(height)*row);
        
        $caret.style.top = pos.top + y + 'px'
        $caret.style.left = pos.left + x + 'px'
        
        // $('span').html("row: " + row + "<br>columns" + col + "<br>width: " + width + "<br>x: " + x +"px<br>y: " + y +"px<br>Scrolltop: "+$(this).scrollTop()).css('top',pos.top+y-$(this).scrollTop()).css('left',pos.left+x+10);
    });
});