0

How can I make it so that if the user types @sometext, the text turns a certain colour where the word starts with @ and ends where there's a space.

For example, let's say the user types the following (and I'm using bold to substitute for colour):

@username this is some text.

I know I have to use the following, but I'm not sure how to continue:

$("textarea").keyup(function() {

}

Please help.

Huangism
  • 16,278
  • 7
  • 48
  • 74
John Smith
  • 2,713
  • 7
  • 24
  • 23
  • Wouldn't that get everything that's in the textarea? – John Smith Nov 19 '13 at 18:52
  • Do you mean that you want to change the color in the textarea, or display the text somewhere else in color? – Guffa Nov 19 '13 at 18:56
  • 1
    Take a look at http://stackoverflow.com/questions/4845813/multicolor-text-highlighting-in-a-textarea-or-text-input – andi Nov 19 '13 at 18:57
  • 3
    You can't style individual words in a textarea – mlienau Nov 19 '13 at 18:58
  • 1
    You want to use contentEditable divs for such styling. – Chandranshu Nov 19 '13 at 18:59
  • @Chandranshu So something like this? ``. How then would I do what I need it to do? – John Smith Nov 19 '13 at 19:07
  • See my answer here: http://stackoverflow.com/questions/19995570/replace-last-character-while-user-typing-in-contenteditable-div/19997193#19997193. The OP had slightly different requirements where he wanted to transliterate the characters into a different language as the user typed. You can adapt it for your use case or open a new question. – Chandranshu Nov 19 '13 at 19:10

1 Answers1

1

To take the text in the textarea and display color coded in a different element, put a tag around each item in the text that you want to set color to, and style that tag.

Example:

$("textarea").keyup(function() {
  $('div').html($(this).val().replace(/(@[^ ]+)/g, '<span>$1</span>'));
});

Demo: http://jsfiddle.net/Guffa/HCt6E/2/

Guffa
  • 687,336
  • 108
  • 737
  • 1,005