JSFiddle - React, Tailwind, and code Playground
by magneto903
HTML
<div id='div' contenteditable="true">
</div>
CSS
#div {
width: 300px;
height: 20px;
border: 2px solid grey;
padding: 20px;
font-size: 20px;
font-family: Arial;
overflow-x: auto;
white-space: nowrap;
}
.key_word {
color: blue;
}
JavaScript
key_words = ['sin']
$.fn.focusEnd = function() {
$(this).focus();
var tmp = $('<span />').appendTo($(this)),
node = tmp.get(0),
range = null,
sel = null;
if (document.selection) {
range = document.body.createTextRange();
range.moveToElementText(node);
range.select();
} else if (window.getSelection) {
range = document.createRange();
range.selectNode(node);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
tmp.remove();
return this;
}
function getCursorPosition(parent) {
let selection = document.getSelection()
let range = new Range
range.setStart(parent, 0)
range.setEnd(selection.anchorNode, selection.anchorOffset)
return range.toString().length
}
function setCursorPosition(parent, position) {
let child = parent.firstChild
while(position > 0) {
let length = child.textContent.length
if(position > length) {
position -= length
child = child.nextSibling
}
else {
if(child.nodeType == 3) return document.getSelection().collapse(child, position)
child = child.firstChild
}
}
}
document.getElementById('div').oninput = function() {
var last_pos = getCursorPosition(document.getElementById('div'))
var expr_1 = document.getElementById('div').innerHTML;
expr_1 = expr_1.replace(/\<span class='key_word'\>/, '');
expr_1 = expr_1.replace(/\<\/span>/, '');
var new_expr_1 = expr_1;
var new_expr_1 = new_expr_1.replace(new RegExp('\\b'+key_words[0]+'\\b', 'g'), "<span class='key_word'>"+key_words[0]+"</span>")
$('#div').empty();
$('#div').append(new_expr_1);
//setCaret($('#div'), false)
//$('#div').focusEnd();
setCursorPosition(document.getElementById('div'), last_pos)
}