Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight text inside textarea like Facebook does

I try to achieve something like the Facebook does when you type @<NAME_OF_A_FRIEND> in a reply. After you choose a friend, the name of that friend is highlighted with a blueish background, so you know it's a separate entity in that text.

I've "inspect element"-ed that textarea and there is no div placed on top of the textarea.

Can anyone give me a clue about how that is done ?

enter image description here

like image 443
Nicu Surdu Avatar asked Dec 08 '11 22:12

Nicu Surdu


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.


2 Answers

I have a completely different approach to this issue using HTML5. I use a div with contentEditable="true" instead of a textarea (wich I was using until I got stuck with the same problem you had).

Then if I want to change the background color of a specified part I just wrapp that text with a span.

I am not 100% sure if it is the correct approach as I am a newbie in HTML5 but it works fine in all the browsers I have tested it (Firefox 15.0.1 , Chrome 22.0.1229.79 and IE8).

Hope it helps

like image 81
José L. Avatar answered Sep 22 '22 22:09

José L.


See this example here. I used only CSS and HTML... The JS is very more complex for now. I don't know exactly what you expect.

HTML:

<div id="textback">     <div id="backmodel"></div> </div> <textarea id="textarea">Hey Nicolae, it is just a test!</textarea> 

CSS:

#textarea {     background: transparent;     border: 1px #ddd solid;     position: absolute;     top: 5px;     left: 5px;     width: 400px;     height: 120px;     font: 9pt Consolas; }  #backmodel {     position: absolute;     top: 7px;     left: 32px;     background-color: #D8DFEA;     width: 53px;     height: 9pt; } 
like image 31
David Rodrigues Avatar answered Sep 20 '22 22:09

David Rodrigues