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.

7
  • Wouldn't that get everything that's in the textarea?
    – John Smith
    Nov 19, 2013 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, 2013 at 18:56
  • 1
    Take a look at stackoverflow.com/questions/4845813/…
    – andi
    Nov 19, 2013 at 18:57
  • 3
    You can't style individual words in a textarea
    – mlienau
    Nov 19, 2013 at 18:58
  • 1
    You want to use contentEditable divs for such styling. Nov 19, 2013 at 18:59

1 Answer 1

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/

1
  • @user623952: Yes, you are correct, I forgot the global flag. Now it works.
    – Guffa
    Nov 19, 2013 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.