I've the below JQuery code, that make coloring for the SQL statement entered in the editable html text:
// SQL keywords
var keywords = ["SELECT","FROM","WHERE","LIKE","BETWEEN", "UNION",
"FALSE","NULL","FROM","TRUE","NOT", "ORDER", "GROUP", "BY", "NOT", "IN"];
// Keyup event
$("#editor").on("keyup", function(e){
// Space key pressed
if (e.keyCode == 32){
var newHTML = "";
// Loop through words
$(this).text().replace(/[\s]+/g, " ").trim().split(" ").forEach(function(val){
// If word is statement
if (keywords.indexOf(val.trim().toUpperCase()) > -1)
newHTML += "<span class='statement'>" + val + " </span>";
else
newHTML += "<span class='other'>" + val + " </span>";
});
$(this).html(newHTML);
// Set cursor postion to end of text
var child = $(this).children();
var range = document.createRange();
var sel = window.getSelection();
range.setStart(child[child.length-1], 1);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
this.focus();
}
});
#editor {
width: 400px;
height: 100px;
padding: 10px;
background-color: #444;
color: white;
font-size: 14px;
font-family: monospace;
}
.statement {
color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="editor" contenteditable="true"></div>
I tried to make it as below: but it failed:
// SQL keywords
var keywords = ["SELECT","FROM","WHERE","LIKE","BETWEEN", "UNION",
"FALSE","NULL","FROM","TRUE","NOT", "ORDER", "GROUP", "BY", "NOT", "IN"];
// Keyup event
document.querySelector('#editor').addEventListener('keyup', e => {
// Space key pressed
if (e.keyCode == 32){
var newHTML = "";
// Loop through words
str = e.target.innerHTML
str.replace(/[\s]+/g, " ").trim().split(" ").forEach(val => {
// If word is statement
if (keywords.indexOf(val.trim().toUpperCase()) > -1)
newHTML += "<span class='statement'>" + val + " </span>";
else
newHTML += "<span class='other'>" + val + " </span>";
});
e.target.innerHTML = newHTML;
// Set cursor postion to end of text
var el = e.target;
el.focus()
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}
});
#editor {
width: 400px;
height: 100px;
padding: 10px;
background-color: #444;
color: white;
font-size: 14px;
font-family: monospace;
}
.statement {
color: orange;
}
<div id="editor" contenteditable="true"></div>
I think my mistake is in returning the cursor to the end of the text field though I tried to implement this