3

I have a textarea that user will type his input in, and I want to change the color for specific words I'm expecting to find in the input string for example I'm expecting the user to type the following:

"My name is Maryam and My age is 24"

so I want to change the color for My name and My age to blue and i want this change to take place once the user type 'My name' or 'My age'. AND TO SHOW THE COLORED TEXT INSIDE THE TEXTAREA..

is there is a way to do this using css, html or javascript ?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Maryam
  • 1,043
  • 1
  • 12
  • 16

2 Answers2

1

It is not possible with text area. But you could fake the result by hidding the textarea and show the color replaced text into another element.

HTML

<textarea onkeyup="textChange()"></textarea>
<div id="colorText"></div>

Javascript:

var textChange=function(){
    var text=event.target.value;

    if(text.indexOf("My name")>-1){
        text=text.replace("My name", "<span class='blue'>My name</span>");
    }

    if(text.indexOf("my age")>-1){
        text=text.replace("my age", "<span class='blue'>my age</span>");
    }

    document.getElementById("colorText").innerHTML=text;
}

css

.blue{
    color:blue;
}
Marteiro
  • 165
  • 1
  • 7
0

I'm not sure if you can change the color of the text in the input field itself. What you can do is have a preview, and when displaying the preview, you can add tags that change the colors of the words you're looking for.

I would suggest implementing this by using a Regex statement to read through the text every time a new character is typed (you can do this with a jQuery "Change" event). Wherever you find these words, put an html tag like around it for the preview. With appropriate CSS styling, these tags can change the colors of the words within them.

master565
  • 805
  • 1
  • 11
  • 27