JSFiddle - React, Tailwind, and code Playground

by janjarfalk

HTML

<input id="element" type="text">

CSS

body {
  padding: 30px;
  background: #fff;
}
input {
  padding: 10px;
  border: 1px solid #777;
  font-size: 24px;
  font-family: Courier;
  outline: none;
}

textarea:focus, input:focus{
    outline: none;
}

JavaScript

const element = document.getElementById('element');

function doGetCaretPosition(oField) {

  // Initialize
  var iCaretPos = 0;

  // IE Support
  if (document.selection) {

    // Set focus on the element
    oField.focus();

    // To get cursor position, get empty selection range
    var oSel = document.selection.createRange();

    // Move selection start to 0 position
    oSel.moveStart('character', -oField.value.length);

    // The caret position is selection length
    iCaretPos = oSel.text.length;
  }

  // Firefox support
  else if (oField.selectionStart || oField.selectionStart == '0')
    iCaretPos = oField.selectionStart;

  // Return results
  return iCaretPos;
}


    function addLink() {
        //Get the selected text and append the extra info
        var selection = window.getSelection(),
        		text = selection + '',
            copytext = text.replace(/[^\d]/g, ''),
            newdiv = document.createElement('div');

        //hide the newly created container
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';

        //insert the container, fill it with the extended text, and define the new selection
        document.body.appendChild(newdiv);
        newdiv.innerHTML = copytext;
        selection.selectAllChildren(newdiv);

        window.setTimeout(function () {
            document.body.removeChild(newdiv);
        }, 100);
    }

    document.addEventListener('copy', addLink);

function setCaretPosition(elem, caretPos) {
  if (elem != null) {
    if (elem.createTextRange) {
      var range = elem.createTextRange();
      range.move('character', caretPos);
      range.select();
    } else {
      if (elem.selectionStart) {
        elem.focus();
        elem.setSelectionRange(caretPos, caretPos);
      } else
        elem.focus();
    }
  }
}

let lastValue = '';
const handleKeyUp = (event) => {
  const position = doGetCaretPosition(element);
  if (lastValue !== element.value && event.keyCode !== 8) {
  ...