I'm trying to make a text editor that formats text based on what it says. For example, when you type "select", it changes the color of the word "select" to red. I'm using a contenteditable
div
.
I was able to make it change the color, but every time I change the text the caret (cursor) moves to the start of the div
.
Here is my example:
var replace = function(text, q, r){
text=text.split(q);
var result = text[0];
for(var i = 1; i < text.length; i++){
result += r + text[i];
}
return result;
};
var run = function(){
document.getElementById('code_editor').innerHTML
= replace(document.getElementById('code_editor').textContent, "select", "<span class='start'>select</span>");
}
$('#code_editor').keyup(function (event) {
run();
});
#code_editor {
width: 600px;
height: 100px;
box-shadow: inset 0px 0px 2px black;
padding: 5px;
overflow-y: scroll;
}
.start {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<code><div id="code_editor" contenteditable tabindex="1"></div></code>