Change color of specific words in textarea
Solution 1:
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>
Solution 2:
JS FIDDLE CODE
HTML-
<div id="board" class="original" contenteditable="true"></div>
<div id="dummy" class="original"></div>
CSS-
.original {
position:absolute;width: 50%; margin: 0 auto; padding: 1em;background: #fff;height:100px;margin:2px;border:1px solid black;color:#fff;overflow:auto;
}
#dummy{
color:black;
}
#board{
z-index:11;background:transparent;color:transparent;caret-color: black;
}
.original span.highlighted {
color:red;
}
JAVASCRIPT -
var highLightedWord = ["select","insert","update","from","where"];
var regexFromMyArray = new RegExp(highLightedWord.join("|"), 'ig');
$('#board').keyup(function(event){
document.getElementById('dummy').innerHTML = $('#board').html().replace(regexFromMyArray,function(str){
return '<span class="highlighted">'+str+'</span>'
})
})
var target = $("#dummy");
$("#board").scroll(function() {
target.prop("scrollTop", this.scrollTop)
.prop("scrollLeft", this.scrollLeft);
});
Solution 3:
With Vanilla JS, you can do it as:
// 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.innerText;
chunks = str
.split(new RegExp(
keywords
.map(w => `(${w})`)
.join('|'), 'i'))
.filter(Boolean),
markup = chunks.reduce((acc, chunk) => {
acc += keywords.includes(chunk.toUpperCase()) ?
`<span class="statement">${chunk}</span>` :
`<span class='other'>${chunk}</span>`
return acc
}, '')
e.target.innerHTML = markup;
// Set cursor postion to end of text
// document.querySelector('#editor').focus()
var child = e.target.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;
}
<div id="editor" contenteditable="true"></div>
Solution 4:
This isn't an answer to this question, but it answers the title question, which is found when you a google search about highlighting a word in a textarea.
A colored selection can be made in a textarea element using the built-in API setSelectionRange function and the ::selection css selector.
Note, it only supports one text selection at a time and only until the textarea gets the focus.
const input = document
.getElementById( 'text-box' );
var i, l;
input.focus();
input.value = input.value.trim();
i = input.value .indexOf( 'programming' );
l = ( 'programming' ).length;
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
input
.setSelectionRange( i, l + i );
::-moz-selection {
background-color: yellow;
color: red;
}
::selection {
background-color: yellow;
color: red;
}
<textarea id="text-box" size="40">
I like programming with JavaScript!
</textarea>
Solution 5:
I couldn't do something about caret so i borrow other people's work and it made code kinda huge. i don't know how fast it is but it works well :T
codes that i borrowed:
https://jsfiddle.net/nrx9yvw9/5/
Get a range's start and end offset's relative to its parent container
you can run with no jquery:
//(sorry for the grammer mistakes)
/*Caret function sources: https://jsfiddle.net/nrx9yvw9/5/ && https://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container/4812022#4812022*/
function createRange(e,t,n){if(n||((n=document.createRange()).selectNode(e),n.setStart(e,0)),0===t.count)n.setEnd(e,t.count);else if(e&&t.count>0)if(e.nodeType===Node.TEXT_NODE)e.textContent.length<t.count?t.count-=e.textContent.length:(n.setEnd(e,t.count),t.count=0);else for(var o=0;o<e.childNodes.length&&(n=createRange(e.childNodes[o],t,n),0!==t.count);o++);return n}function getCurrentCaretPosition(e){var t,n=0,o=e.ownerDocument||e.document,a=o.defaultView||o.parentWindow;if(void 0!==a.getSelection){if((t=a.getSelection()).rangeCount>0){var r=a.getSelection().getRangeAt(0),c=r.cloneRange();c.selectNodeContents(e),c.setEnd(r.endContainer,r.endOffset),n=c.toString().length}}else if((t=o.selection)&&"Control"!=t.type){var i=t.createRange(),g=o.body.createTextRange();g.moveToElementText(e),g.setEndPoint("EndToEnd",i),n=g.text.length}return n}function setCurrentCaretPosition(e,t){if(t>=0){var n=window.getSelection();range=createRange(e,{count:t}),range&&(range.collapse(!1),n.removeAllRanges(),n.addRange(range))}}
/*Caret functions end*/
/*
* -> required | [...,...] -> example | {...} -> value type | || -> or
id: Position of words for where they should be colored [undefined,0,1,...] {int||string}
color: Color for words [aqua,rgba(0,255,0,1),#ff25d0] {string}
fontStyle: Font style for words [italic,oblique,normal] {string}
decoration: Text decoration for words [underlined,blink,dashes] {string}
* words: Words that should be colored {array}
*/
var keywords = [
{
color: "orange",
words: [
"SELECT",
"FROM",
"WHERE",
"LIKE",
"BETWEEN",
"NOT",
"FALSE",
"NULL",
"TRUE",
"IN",
],
},
{
id: 0,
color: "red",
fontStyle: "italic",
decoration: "underline",
words: ["TEST"],
},
];
//defining node object as "editor"
var editor = document.getElementById("editor");
//listening editor for keyup event
editor.addEventListener("keyup", function (e) {
// if ctrl or alt or shift or backspace and keyname's length is not 1, don't check
if( e.ctrlKey || e.altKey || ( e.key.length - 1 && e.key != "Backspace" ) || ( e.shiftKey && e.char ) ) return;
//getting caret position for applying it in the end, because after checking and coloring done; it's gonna be at the beginning.
pos = getCurrentCaretPosition(this);
text = this.innerText; //getting input's just text value
words = text.split(/\s/gm); //splitting it from all whitespace characters
for (var i = 0; i < keywords.length; i++)
for (var n = 0; n < words.length; n++) {
//looks for is word in our "keywords"' object and check's position if it's id entered
if (keywords[i].words.indexOf(words[n].toUpperCase().trim()) > -1 && (keywords[i].id >= 0 ? keywords[i].id == n : true) )
//applys options to word
words[n] = `<span style="color:${ keywords[i].color ?? "white" };font-style:${ keywords[i].fontStyle ?? "normal" };text-decoration:${ keywords[i].decoration ?? "normal" }">${words[n]}</span>`;
}
//joining array elements with whitespace caracter and apply it to input
this.innerHTML = words.join(" ");
//restoring caret position
setCurrentCaretPosition(this, pos);
});
#editor {
width: 400px;
height: 100px;
padding: 10px;
background-color: #444;
color: white;
font-size: 14px;
font-family: monospace;
font-weight: normal;
caret-color: white;
}
<div id="editor" spellcheck="false" contenteditable="true"></div>