JSFiddle - React, Tailwind, and code Playground
HTML
<div class="typeable" contenteditable="true">Type "@test" after this text: </div>
CSS
.typeable {
padding: 15px;
border: 1px solid #ccc;
border-radius: 2px;
width: 500px;
min-height: 75px;
}
JavaScript
var userPressedAt = false;
function highlight() {
var el = $('.typeable')[0],
str = $('.typeable').text(),
range = document.createRange(),
sel = window.getSelection(),
start,
end;
start = str.lastIndexOf('@');
end = str.length;
range.setStart(el.childNodes[0], start);
range.setEnd(el.childNodes[0], end);
sel.addRange(range);
el.focus();
document.execCommand('foreColor', false, 'red');
sel.collapseToEnd();
document.execCommand('foreColor', false, 'black');
}
function highlighter(e) {
if (e.which === 50) {
userPressedAt = true;
}
if (userPressedAt && e.which === 32) {
highlight();
}
}
$('.typeable').on('keyup', highlighter);