1

Let's say I have a textarea and bold button for like that:

<div class="main">
  <textarea  cols="60" rows="12">
     Lorem ipsum dolor sit amet...
  </textarea>
</div>

<br>
<button onclick="bold()">Bold</button>

when I select (highlight) the content with the mouse and click on the bold button, I would like it to wrap the selection with tag, for example:

<b>content</b>

That's what I have so far but:

bold = function()  {       
    var selection = window.getSelection().getRangeAt(0);
    var selectedText = selection.extractContents();
    var span = document.createElement("b");     
    span.appendChild(selectedText);
    selection.insertNode(span);
}
  1. How can I make it to work with textrea too
  2. How can I make it to work only for the main div

jsfiddle: https://jsfiddle.net/5feLm4jn/3/

user4571629
  • 440
  • 3
  • 10
  • 24

2 Answers2

0

As of today, there is no way to enable rich text formatting within a <textarea>. You'll have to use a <div> with the contenteditable attribute. For example:

<div id="foo" contenteditable> ... </div>

A full viable explanation (along with a JSFiddle example) has been provided already: Make selected text bold/unbold

Hope it helps!

Community
  • 1
  • 1
0

Using a content editable div, you can directly use the document.execCommand to bold the selected text in your document.


Snippet :

function bold() {
  document.execCommand('bold');
}

function getSelectedText() {
  var html2 = "",
    html_changed = "";
  if (window.getSelection) {
    html2 = window.getSelection().toString();
  } else if (document.selection && document.selection.type != "Control") {
    html2 = document.selection.createRange().text;
  }
  html_changed = "<div>" + html2 + "</div>";
  var temp = document.getElementById("div");
  var temp_text = "";
  temp_text = temp.innerHTML;
  var str = temp_text;
  str = str.replace(html2, html_changed);
  temp.innerHTML = temp_text;
}
<div class="main" contenteditable id="div">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas, asperiores quidem ab neque molestias voluptatum amet possimus dolore rem enim error, eaque pariatur adipisci praesentium consequuntur! Rerum maxime eveniet ipsam est voluptas, facere
  sequi cupiditate dolor exercitationem aspernatur distinctio in animi beatae earum! Ducimus provident ipsa vero in natus unde consequuntur ut, sapiente, reiciendis cumque illum exercitationem inventore asperiores enim architecto! Eveniet unde ipsa laudantium
  facilis placeat obcaecati quam magnam quibusdam.
</div>

<br>
<button id="bold" onclick="getSelectedText()">Bold</button>
stark
  • 2,246
  • 2
  • 23
  • 35