I am making a text editor, and I want to have a feature, such that while typing, if the user enters some keyword (e.g. happy, sad), the word is automaticly styled (e.g. color changed). How might I go about doing this?
document.getElementById('texteditor').addEventListener('keyup', function(e) {
styleCode(); //Style the text input
});
//Change the result of pressing Enter and Tab keys
document.getElementById('texteditor').addEventListener('keydown', function(e) {
switch (e.key) {
case 'Tab':
e.preventDefault();
document.execCommand('insertHTML', false, ' '); //Insert a 4-space tab
break;
case 'Enter':
e.preventDefault();
document.execCommand("insertLineBreak"); //Insert a new line
break;
}
});
function styleCode(){
//Style the code in the input box
}
#texteditor {
border: 3px solid black;
width:100%;
height: 500px;;
overflow:auto;
flex:1;
word-wrap: break-word;
word-break: break-all;
white-space:pre-wrap;
padding:5px;
font-family: Consolas,"courier new";
font-size:14px;
}
.styleA {
color:red;
}
.styleB {
color:blue;
}
<div id='texteditor' contenteditable></div>
Basically, when the user fully types "happy" (upon releasing the 'y' key) the word "happy" should turn red (using the styleA CSS class) in the editor. A similar thing should happen when the user finishes typing "sad"; the word "sad" should turn blue using the styleB CSS class.
Thanks in advance for any help.