Skip to content
Advertisement

Is there a way to have different colored text inside a textarea?

I have an HTML Textarea, which contains a custom-made live editable JSON file where you can see the results of the edits in real-time. I also have something that can cycle through the entries in a “points” attribute, being a list, where it shows the results in the canvas where the JSON results are seen, such that one can see what point is being selected.

I want the point in the textarea to be able to be formatted when selected, such as the selected point in the textarea JSON to be highlighted yellow or have the text color changed to blue or something like that.

I have tried this:

<textarea id="objtext">
  not orange 
  <span style="color:orange"> 
    orange 
  </span>
  not orange 
</textarea>

It just showed the textarea having that in it as text, instead of formatting inside the textarea.

How do I make it formatted (and editable and readable by code with textarea.value ideally without the formatting)?

Advertisement

Answer

I don’t think this is possible with textarea. I think epascarello is trying to tell you that it is possible using a div with the attribute contenteditable="true".

Check out this similar question – Is it possible to have several different textcolors in one textarea?

You will need to style the div to look and feel like a textarea. Here’s a basic mockup, you may need to add some Javascript to extend this.

<div id="objtext" contenteditable="true">
  not orange 
  <span class="orange-text"> 
    orange 
  </span>
  not orange 
</div>

#objtext {
  -moz-appearance: textfield-multiline;
  -webkit-appearance: textarea;
  border: 1px solid gray;
  overflow: auto;
  padding: 4px;
  width: 400px;
  height: 200px;
  font: medium -moz-fixed;
  font: -webkit-small-control;
}

.orange-text {
  color: orange;
}

::selection {
    color:orange;
}

::-moz-selection {
    color:orange;
}

https://jsfiddle.net/miainchambers/g07rcb5o/2/

Text value can be retrieved by using document.getElementById("objtext").textContent

Advertisement