1

I'm wondering if it's possible to change just a section of the a text input box's color. I am creating a comment widget want everything between the @ and the : to change to a different color:

<input type="text" placeholder="Want To Say Something?" 
value="@user556: This is a test comment" ng-model="Comment" ng-click="getCurrentPosition()" 
class="form-control ng-valid valid ng-dirty">

Is this possible to do with jQuery or javascript? Or do I have to convert the text input to a div?

user547794
  • 14,263
  • 36
  • 103
  • 152
  • 1
    maybe you can wrap the part your want to color in a span tag and then style that – Alex_Nabu Apr 01 '14 at 15:48
  • text inputs and textareas cannot have multiple colors for the text. A simple solution would be to provide a preview `div` below the input – Patrick Evans Apr 01 '14 at 15:51
  • Take a look at how twitter does this - they use `div`s and `span`s to achieve the same when the amount of characters in the tweet exceeds 160 – callmekatootie Apr 01 '14 at 17:10

1 Answers1

0

Possible, within a contenteditable element,
and with some JS and a bit of RegExp to replace the desired match:

function colorify() {
  this.innerHTML = this.textContent.replace(/@([^:]+):/g, "@<span class='user'>$1</span>:");
}

function uncolorify() {
  this.innerHTML = this.textContent;
}

[].forEach.call(document.querySelectorAll(".comment"), function(el){
  el.addEventListener("blur",    colorify);
  el.addEventListener("focus", uncolorify);
});
[contenteditable] {
  background:#fafafa;
  padding:8px;
  border-radius:3px;
  border:1px solid #ddd;
}
[contentEditable]:empty:not(:focus):before {
  /*http://stackoverflow.com/a/18368720/383904*/
  content: attr(data-placeholder);
  color: #777;
}
.user{
  color: #f0f;
}
(Copy the following text into the contenteditable)<br>
@user547794: Use contenteditable. @johnDoe: nice suggestion btw.
<div class="comment" contenteditable data-placeholder="Want To Say Something?"></div>
Than click outside of the contenteditable.
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313