textarea caret xy coordinate

https://medium.com/@_jh3y/how-to-where-s-the-caret-getting-the-xy-position-of-the-caret-a24ba372990a

by tnhu

HTML

<input>
<textarea></textarea>
  <span class="indicator"></span>

CSS

body {
  padding: 0;
  margin : 0;
}
.indicator {
  height: 14px;
  width : 14px;
  display: block;
  position: absolute;
  background: red;
}

JavaScript

(function() {
  var text = document.querySelector('input'),
      indicator = document.querySelector('.indicator'),
    getCoord = function(e) {
      var carPos = text.selectionEnd,
        div = document.createElement('div'),
        span = document.createElement('span'),
        copyStyle = getComputedStyle(text),
        coords = {};
      [].forEach.call(copyStyle, function(prop){
        div.style[prop] = copyStyle[prop];
      });
      div.style.position = 'absolute';
      document.body.appendChild(div);
      div.textContent = text.value.substr(0, carPos);
      span.textContent = text.value.substr(carPos) || '.';
      div.appendChild(span);
      coords = {
        TOP: span.offsetTop,
        LEFT: span.offsetLeft
      };
      console.log(coords);
      indicator.style.left = text.offsetLeft - text.scrollLeft + coords.LEFT + 'px';
      indicator.style.top  = text.offsetTop - text.scrollTop + coords.TOP  + 14 + 'px';
      document.body.removeChild(div);
    };
  text.addEventListener('keypress', getCoord);
}());