Question

I want to highlight the text inside the textarea as facebook does. A solution to this is to keep an external div and highlight, as in this fiddle. But then there might be multiple highlighted field and then there position and width will have to be calculated at every instant, which seems very complex. Also backspace should remove the complete tag at once. Any way in which these hashtags can be implemented or any sample code implementing the same technique above?

As Html is highlighted here

Was it helpful?

Solution

The highlighting is occurring on a background layer that is updated on a keyup event listener (the textarea is transparent (background-color: rgba(0,​ 0,​ 0,​ 0))). This is what it looks like if you add some padding-top to the textarea (the highlight doesn't have an opportunity to update):

enter image description here

Facebook's approach is actually really clever, as you type in the text area the contents are evaluated and sent to a background element that looks like this:

<span class="highlighterContent"><b>#html</b> This is </span>

The <b> element has the following css:

.uiMentionsInput .highlighter b {
    background: linear-gradient(#DCE6F8, #BDCFF1) repeat scroll 0 0 rgba(0, 0, 0, 0);
    border-radius: 2px;
    box-shadow: 0 0 0 1px #A3BCEA;
    font-weight: normal;
}

The smart thing is the span behind the text area has a transparent font so it takes the same space as the opaque font of the text area (allowing the <b> highlight to stay aligned with the textarea text). Smart guys over there :)

OTHER TIPS

you can make something like this:

http://jsfiddle.net/HR5N8/

<div id="something" contentEditable="true">
    Hi, my name is <span class="name">John</span> and i'm 20 years old!    
</div>

#something{
    width: 400px;
    height: 100px;
    border: 1px solid grey;
}

.name{
     background: #E1EEF5;   
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top