Change color of specific words in textarea
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 keywordsvar 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>
Change style/color of a only word in textarea? NOT DIV
You really can't do this with a textarea. Fortunately you can use a div to emulate a textarea so you can still edit within it by adding contenteditable="true"
to the tag
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content
How to change color of text in a textarea
Unfortunately, you can't add markup inside a textarea
, but here is an idea you could take as a starting approach, it comes from this link. The approach will be based on this:
The basic idea is to carefully position a
<div>
behind the<textarea>
. ThenJavaScript
will be used to copy any text entered into the<textarea>
to the<div>
. A bit moreJavaScript
will make that both elements scroll as one. With everything perfectly aligned, we can add markup inside the<div>
to give colors to some particular words, and we going to set text color to transparent on the<textarea>
, completing the illusion.
Base Implementation:
// Initialization.
const colorMap = {"apple": "red", "market": "green", "banana": "orange"};
let textArea = document.getElementById("myTextArea");
let customArea = document.querySelector(".custom-area");
let backdrop = document.querySelector(".backdrop");
// Event listeners.
textArea.addEventListener("input", function()
{
customArea.innerHTML = applyColors(textArea.value);
});
textArea.addEventListener("scroll", function()
{
backdrop.scrollTop = textArea.scrollTop;
});
function applyColors(text)
{
let re = new RegExp(Object.keys(colorMap).join("|"), "gi");
return text.replace(re, function(m)
{
let c = colorMap[m.toLowerCase()];
return `<spam style="color:${c}">${m}</spam>`;
});
}
.backdrop, #myTextArea {
font: 12px 'Open Sans', sans-serif;
letter-spacing: 1px;
width: 300px;
height: 100px;
}
#myTextArea {
margin: 0;
position: absolute;
border-radius: 0;
background-color: transparent;
color: transparent;
caret-color: #555555;
z-index: 2;
resize: none;
}
.backdrop {
position: absolute;
z-index: 1;
border: 2px solid transparent;
overflow: auto;
pointer-events: none;
}
.custom-area {
white-space: pre-wrap;
word-wrap: break-word;
}
<div class="container">
<div class="backdrop">
<div class="custom-area">
<!-- Cloned text with colors will go here -->
</div>
</div>
<textarea id="myTextArea"></textarea>
</div>
Javascript change font color when using textarea
.textarea_type_div{ width: 1300px; height: 857px; background-color: #333333; font-family: Arial; font-size: small; font-weight: normal; color: #FFFFFF;}
.textarea_type_div .studentname{ font-weight:bold; color:red;}
.textarea_type_div .studentnumber{ font-weight:bold; color:blue;}
<div class="textarea_type_div" contenteditable="true"> <span class="studentname">Student Name</span> <span class="studentnumber">Student Number</span></div>
Change color of TextArea words
qooxdoo does use a native TextArea so it depends on the native TextAreas capabilities. As TextAreas do not support that feature, we can't do much about it.
See also answers on the following questions for further information:
Change the Color Of Certain Words In Textarea using Jquery?
Multicolor Text Highlighting in a Textarea or Text Input
Setting a different color only for words which came out of dropdown in textarea editor(angular)
Update 04-04-2021 please take a look to Owen Kevin's answer in this SO because my code don't take account the "scroll"
the only way to "highlight" text inside a textarea is to have two layers, one with a text area and another one with a div with [innerHtml]
the problem with a textarea is that you need use the same font-family than the div
from this codePen the .html like
<div class="container" [style.width]="text.getBoundingClientRect().width+'px'"
[style.height]="text.getBoundingClientRect().height+'px'">
<div class="backdrop">
<div class="highlights" [innerHtml]="textFormatted"></div>
</div>
<textarea #text [ngModel]='textValue' (ngModelChange)="change($event)" rows="10" cols="40">
</textarea>
</div>
A function "formatted"
formatted(message:string)
{
return message.replace(/\n/g, "<br />").replace(this.regExpr,"<mark>$&</mark>")
}
replace the message with the "mark" in the words selecteds
regExpr=new RegExp(this.list4.map(x=>'('+x+')').join('|'),"g");
Remember call to this.formatted each time you change the textarea
changeValue(ev) {
this.textValue += ` ${ev.value}`;
this.textFormatted=this.formatted(this.textValue);
}
change(message:string)
{
this.textValue = message;
this.textFormatted=this.formatted(this.textValue);
}
And, behare! the .css to change the mark should be in the styles.css
The stackblitz
Update if we want to change into italic is that we need made transparent the text-area color and colored the "hightlight". This make "loose" the cursor.
.highlights {
...
color: #444;
}
textarea {
....
color: transparent;
}
We can use -webkit-text-fill-color but it's not a standards css (works on FireFox, Chrome and Edge)
@supports (-webkit-text-stroke: 1px black) {
textarea {
color:#444;
-webkit-text-stroke: 1px transparent;
-webkit-text-fill-color: transparent;
}
}
The modiffied stackblitz
How can i change the specific character color in the textarea using jquery?
Here is a solution. but jQuery code runs only once
var alpha = ["s","x","e","T"];var res = "", cls = "";var t = $("#txt").text();
for (i=0; i<t.length; i++) { for (j=0; j<alpha.length; j++) { if (t[i] == alpha[j]) {cls = "red";} } res += "<span class='"+cls+"'>"+t[i]+"</span>"; cls="";}$("#result").html(res);
.red { color: red;}#result { font-size: 24px; font-weight: bold;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><textarea id="txt">This is a line of text for test.</textarea><div id="result"></div>
Related Topics
How to Create an Asynchronous Function in JavaScript
5Xx or 4Xx Error with "No 'Access-Control-Allow-Origin' Header Is Present"
Parse Date Without Timezone JavaScript
Add a "Hook" to All Ajax Requests on a Page
Es6 Variable Import Name in Node.Js
How to Mock an Es6 Module Import Using Jest
Event.Returnvalue Is Deprecated. Please Use the Standard Event.Preventdefault() Instead
Webhoster Inserts a JavaScript Which Brokes My Code How to Remove It
Get Video Duration When Input a Video File
Get Value of Input Field Inside an Iframe
How to Select Element That Does Not Have Specific Class
Attach an Event in a Child Iframe to a Handler in the Parent Window
Create Table with Jquery - Append
Ignore Mouse Interaction on Overlay Image
Retrieving File Names Out of a Multi-File Upload Control with JavaScript
Remove Whitespaces Inside a String in JavaScript