You can’t change the colours of words in a <textarea>
, but you can use the contenteditable
attribute to make a <div>
, <span>
, or <p>
look like a <textarea>
.
To do this you can use a JavaScript plugin, but if you want to create a new one, the code below may help you.
For this purpose, you need to get any word in the text. Then check that if it’s a SQL keyword.
// SQL keywords
var keywords = ["SELECT","FROM","WHERE","LIKE","BETWEEN","NOT LIKE","FALSE","NULL","FROM","TRUE","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://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="editor" contenteditable="true"></div>