JSFiddle - React, Tailwind, and code Playground
HTML
<html><head /><body><span class="replaceMe">Does this textarea swap trick work?<br />I sure hope so.<br />Otherwise I'm wasting my time here.</span>
CSS
.replaceMe {
font-family: monospace;
}
JavaScript
source = document.getElementsByClassName('replaceMe')[0];
source.onclick = replaceAndSet;
function replaceAndSet(e) {
var userRange;
if (window.getSelection) {
userRange = window.getSelection().getRangeAt();
}
newInput = createInput(source);
source.setAttribute('hidden','');
document.body.appendChild(newInput);
var spanLines = userRange.startContainer.parentElement.childNodes;
var clickChar = getCursorLoc(spanLines, userRange);
newInput.focus();
newInput.setSelectionRange(clickChar, clickChar);
}
function createInput(baseEl) {
baseX = baseEl.offsetLeft; baseY = baseEl.offsetTop;
baseWidth = baseEl.offsetWidth; baseHeight = baseEl.offsetHeight;
textBox = document.createElement('TextArea');
textBox.setAttribute('style',
'position: absolute; '+
'font-family: monospace; '+
'left: '+baseX+'px; '+
'top: '+baseY+'px; '+
'width: '+baseWidth+'px; '+
'height: '+baseHeight+'px;')
textBox.className = "testInput";
textBox.defaultValue = baseEl.innerText; // .replace(/<br>/g,'\r\n');
return textBox;
}
function getCursorLoc (nodes, range) {
var prevChars = 0;
var clickContent = range.startContainer.textContent;
var clickLine;
for (x = nodes.length - 1; x >= 0; x--) {
node = nodes[x];
if (clickContent == node.textContent) {
clickLine = x;
}
else if (clickLine && (node.nodeName == "#text") ) {
prevChars += node.textContent.length + 1;
}
}
return range.startOffset + prevChars;
}