Reputation: 386
Please i need to change color of a single character in textarea using JQuery.
Upvotes: 1
Views: 8243
Reputation: 4661
Change color of @ Username # Hashtag and link with clickable
Pure Vanilla JavaScript
const linkGenerator = ( contentElement, baseUrl ) => {
const elem = document.querySelector(contentElement);
elem.innerHTML = elem.innerHTML
.replace(/(https?:\/\/[^\s]+)/g, `<a class='link' href="$1">$1</a>`)
.replace(/(@[^\s]+)/g, `<a class='username' href='${baseUrl}/$1' title='$1'>$1</a>`)
.replace(/(#[^\s]+)/g, `<a class='hashtag' href='${baseUrl}/$1'>$1</a>`)
return elem
}
linkGenerator( '#myContent', 'https://www.any-domain.net');
linkGenerator( '#myContent2', 'https://www.any-domain.org');
.link { color: navy; }
.username { color: green; }
.hashtag { color: orange; }
<div id="myContent">Dear @You, Welcome to @StackOverflow</div>
<div id="myContent2">Hello @World, from @GMKHussain
Trending now! #Hastag
https://any-domain.net
</div>
Upvotes: 0
Reputation: 362
Use this jQuery plugin: jQuery.colorfy
https://github.com/cheunghy/jquery.colorfy
Demo here: http://cheunghy.github.io/jquery.colorfy/
Upvotes: 0
Reputation: 386
I changed the textarea by a content editable div:
<div contenteditable="true"></div>
div {width:98%;clear: both;font-size: 10pt;max-width:98%;height:250px;min-height:98%;
left:10px;right:10px;background-color:#fff;border:1px solid #1c578d;bottom:10px;top:10px;color:#1B4A90;overflow:auto;
display:inline;}
Upvotes: 3
Reputation: 3633
You can't change colors, but what you can do is select a particular character (highlight by way of JavaScript.)
See Highlighting a piece of string in a TextArea
Upvotes: 0
Reputation: 13755
The only way to do that would be to create your own "element". For example, create an empty div
, and a focus handler which would enable the key press listener - the key press handler would then at the pressed character to the html of the div. If the char is the one (or one of those) you want you'd add a span
(for example) around it to style it. Of course, you'll have to be able to handle things such as holding down a keyboard key should keep adding the same char, also you'd need to handle deleting via delete, backspace, and selection, etc. A lot of stuff to do just to be able to highlight a char.
Upvotes: 0
Reputation: 377
This isn't a full answer, but in HTML5 there is the contenteditable attribute. Here is a link to an example. This does support specific styling.
Upvotes: 0
Reputation: 324600
You can't. A textarea is plain text only. That's why, for example, HTML inside a textarea is rendered literally (except for </textarea>
).
Upvotes: 3