1

I need to change the text color from an selected text in a textarea, when I click on a Button.

My first try:

document.getSelectedText(document.getElementById('test22')).style.color = '#0F0';

My secound try:

document.getSelectedText((test22.value).substring(test22.selectionStart, test22.selectionEnd)).style.color = '#0F0';

HTML code:

<textarea name="area1" cols="40" id="test22"></textarea>
<button onclick="test();">CLICK</button>

Thank you! ;)

Tuxio
  • 15
  • 3
  • Problably a duplicate of this: http://stackoverflow.com/questions/17288964/how-to-change-color-of-the-selected-text-dynamically-on-click-of-button – Mijago Jan 22 '16 at 16:34
  • yes, but I need this for an texarea. This only works for a "normal" text. – Tuxio Jan 22 '16 at 16:37
  • Sorry :) I will look again to help you :) – Mijago Jan 22 '16 at 17:03
  • Here is sample of solution with span element https://stackoverflow.com/questions/17288964/how-to-change-color-of-the-selected-text-dynamically-on-click-of-button – Nezir Sep 29 '18 at 10:15

2 Answers2

0

There is no way to set this up in Textareas, because they are not ment to be RTF Editors.

You can use the contenteditable="true" tag with a div and do the magic there, just like setting "font" tags here and there.

You could also use something like https://www.tinymce.com or http://ckeditor.com . Both are WYSIWYG-Editors. Or search for any light RTF-Editor on github.

And maybe you can get some ideas from this: http://dipaksblogonline.blogspot.in/2014/11/javascript-text-selection-popover.html

Mijago
  • 1,569
  • 15
  • 18
0

Is this an option?

Demo - codepen.io

document.querySelector(".my-button").addEventListener("click", myFunction);

function myFunction() {
let elem = document.querySelector("#note_text");
  elem.classList.add("add-color");
  elem.focus();
}
#note_header::selection {
  color: red;
}

.add-color::selection {
  color: red;
}
<h3>Level - 1</h3>

<textarea id="note_header" rows="7" cols="70">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</textarea><br>

<h3>Level - 2</h3>

<textarea id="note_text" rows="7" cols="70">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.</textarea><br>
<button class="my-button">CLICK</button>
Pedro404
  • 158
  • 5