Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multicolor Text Highlighting in a Textarea or Text Input

I'd like to set text in a textarea or text input using different colors (one or the other is fine, I don't need both). Think of something like simple syntax highlighting. So, let's say I have some keywords defined. I'd like those words to be colored a different color as the user types into the textarea or text input

I understand this needs to be some combination of CSS, Javascript, and maybe some pixie dust. I wondering which direction I need to dig into to find out how this can be done.

Thank you

like image 848
oneself Avatar asked Jan 30 '11 21:01

oneself


People also ask

How do you highlight text in textarea?

You can't actually highlight text in a <textarea> . Any markup you would add to do so would simply display as plain text within the <textarea> . The good news is, with some carefully crafted CSS and JavaScript, you can fake it.

How do you highlight text in input?

For selecting the content of an input (with highlight), use: el. select() . For css manual highlight, see @HashemQolami answer.

How do you make a multicolor text?

Another way is creating a text with separate elements by using the HTML <span> tag, which is an empty container. This means that you create a multicolor text by putting each letter in a separate element to define a different color for each letter of your text.


2 Answers

No, you can't do this in a textarea or text input. Any CSS text-related property will affect the whole text within the the textarea/input. You'll need an editable element or document to achieve syntax highlighting. Example (works in all recent browsers; the last major browser not to support contenteditable was Firefox 2.0):

<code contenteditable="true">    <span style="color: blue">var</span> foo = <span style="color: green">"bar"</span>;  </code>
like image 109
Tim Down Avatar answered Sep 28 '22 05:09

Tim Down


Are you finding this?

Use jQuery.colorfy

Code: https://github.com/cheunghy/jquery.colorfy

Demo: http://cheunghy.github.io/jquery.colorfy/

Screencast: https://www.youtube.com/watch?v=b1Lu_qKrLZ0

like image 20
Zhang Kai Yu Avatar answered Sep 28 '22 05:09

Zhang Kai Yu