I have a textarea with some lines of text. The text contains alpha, numeric and special characters. I would like to apply CSS background colors on only some words (just to highlight them) within that text. For example, apply background color to only numbers in the textarea. Please let me know how to accomplish this. Suggestions are appreciated.
-
1You're going to have to use some fancy JS to do this. Also, show your code. – Kyle Oct 16 '12 at 06:46
-
You can only add styles to elements, so each word or group of characters that you want to colorize needs to be surrounded with some element to group is, like a ``. – w5l Oct 16 '12 at 06:47
-
what you have done till now to achieve that ? – Ratan Kumar Oct 16 '12 at 06:48
-
4It's cute that so many of the answers assume you can embed HTML in a ` – BoltClock Oct 16 '12 at 09:00
-
1Not really a duplicate question, but this similar question may provide you with your solution http://stackoverflow.com/questions/1619167/textarea-that-can-do-syntax-highlighting-on-the-fly – Josh Davenport-Smith Oct 16 '12 at 09:05
-
@JoshDavenport - good link. I have had great experience with CodeMirror (mentioned in the accepted answer). – Tim M. Oct 16 '12 at 09:18
3 Answers
There is no way (that I know of) to do this using pure HTML and CSS. You're going to have to use some JavaScript.
Option 1 Use an existing jQuery plugin. A quick search led me to this and the updated plugin here.
Option 2 Roll your own. You would want to consider using the search() function to find the location of the words, then adding span wrappers around the words.
<style>.highlighted{background-color:yellow;}</style>
...
<span class="highlighted>HIGHLIGHT ME</span>
The only real advantage of this is that you can use regular expressions to allow for more flexibility in what you're highlighting. It also allows you to avoid jQuery if it's not your cup of tea.

- 23
- 3
The only way I can think to do this will be to wrap the required text in some html to style it. To do this I recoomend having a seperate output for the textarea text, see here: http://jsfiddle.net/mhPGc/8/

- 551
- 2
- 7
-
1It's slightly buggy, but why not bind to the `keydown` event on the `textarea` http://jsfiddle.net/mhPGc/5/ – Josh Davenport-Smith Oct 16 '12 at 09:01
-
1although if you keep it as keydown then you are always one character check behind, updated here http://jsfiddle.net/mhPGc/8/ – JamieM23 Oct 16 '12 at 09:08
You use span tag for this issue,you first set id for text area then use this style code
#textarea span{
background:url(img.jpg) or #etc;
}

- 3,415
- 3
- 24
- 41