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
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.
For selecting the content of an input (with highlight), use: el. select() . For css manual highlight, see @HashemQolami answer.
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.
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With