JSFiddle - React, Tailwind, and code Playground
by Qwerty_Wasd
HTML
<script src="http://rangy.googlecode.com/svn/trunk/currentrelease/rangy-core.js"></script>
<div contenteditable="true">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
<br />It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
<h3>Variable value:</h3>
<span></span>
CSS
span {
background-color: #EFEFEF;
}
JavaScript
$("div").keydown(function () {
// Get the current selection with Rangy
var sel = window.getSelection()
// Insert a temporary caret element at the caret position
// (which is inside the contenteditable element)
if (sel.rangeCount) sel.getRangeAt(0).insertNode($("<caret />")[0]);
// Read the html inside the contenteditable element
var innerHTML = $("div").html();
// Clean up, get rid of the caret element
$("caret").remove();
// Only keep the text before the first occurrence of the caret element
innerHTML = innerHTML.substr(0, innerHTML.indexOf('<caret>'));
$("span").text(innerHTML);
});