Prompt by this feature. Where to call her?

The problem: there is a textarea field, at the top of the link. When clicking on a link, the text should be formatted, but this does not happen. Here is the code:

window.onload = function () { var mainDiv = document.createElement('div'); mainDiv.id = 'mainDiv'; document.body.appendChild(mainDiv); var buttonControl = { 'paragraf': '<a href = "#paragraf" id="paragraf" class="buttonControl">p</a>', 'bold': '<a href = "#bold" id="bold" class="buttonControl">b</a>', 'italic': '<a href = "#italic" id="italic" class="buttonControl">i</a>' }; for (var property in buttonControl) { mainDiv.innerHTML += buttonControl[property]; } var mainArea = document.createElement('textarea'); mainArea.id = 'mainArea'; mainDiv.innerHTML += '<br />'; mainDiv.appendChild(mainArea); document.getElementById('bold').onclick = function (element) { mainArea.focus(); window.document.execCommand('bold', null, ''); element.preventDefault(); }; }; 
  • The tag does not work with the Code, sorry - systemiv
  • @systemiv There must be an empty line between the previous text and the code block, then it will be formatted. - Nicolas Chabanovsky

1 answer 1

First, for execCommand() to work, you must enable designMode or contentEditable — look, for example, at the Mozilla docks . Secondly, you cannot format text in textarea in this way - this element always stores only text. However, you can format the text, for example, in a diva (before clicking on a link, select the text in editDiv ):

 ... for (var property in buttonControl) { mainDiv.innerHTML += buttonControl[property]; } var editDiv = document.createElement('div'); editDiv.id = 'editDiv'; editDiv.innerHTML = "123123"; document.body.appendChild(editDiv); document.getElementById('bold').onclick = function (event) { editDiv.contentEditable = true; window.document.execCommand('bold', false, ''); editDiv.contentEditable = false; event.preventDefault(); };