Trying to make a personal HTML editor. With textarea, everything works as it should: ( CodePen-1 )
If nothing is selected, tags are added simply at the end of the printed text. And if you select the text - when you click on the button, the text is placed inside the tags.
<button title="division" class="tag" onclick="tag('<div>','</div>');">div</button> <textarea id="form"></textarea>
Js:
function tag(a,b){ var x = document.getElementById('form'); x.focus(); var value = $("#form").val(); var start=x.selectionStart; var end=x.selectionEnd; var selected = a + value.substr(start,end-start) + b; $("#form").val( value.substr(0,start) + selected + value.substr(end) ); }
But the interior of the Textarea is impossible to paint or somehow select, so there is a need to make an editable div in which you can already highlight keywords or tags. But selectionStart and selectionEnd do not work here ( CodePen-2 ):
<button title="division" class="tag" onclick="tag('<div>','</div>');">div</button> <div id="form" contenteditable="true"></div>
Js:
function tag(a,b){ var x = document.getElementById('form'); var value = $("#form").text(); var start = x.selectionStart; var end = x.selectionEnd; var selected = a + value.substr(start,end-start) + b; $('#form').text( value.substr(0,start) + selected + value.substr(end) ); x.focus(); }
The spear method did not work and it is not clear what I am doing wrong. Apparently you just need to know ...