1

Ive built a little bit of code which adds text to a text area box depending on which button is pressed a very simple editor if you like.

Currently the code just inserts the selected text where the cursor is, but if text is highlighted then I would like it to wrap that text as well.

I have a jsfiddle at http://jsfiddle.net/gffeab94/3/

but for clarity the the function is

jQuery("document").ready(function($){

  $('#bold').on('click', function () {
  _insertAtCaret($('#transcription-page-wikitext'), "'''bold text here'''");
});

$('#italic').on('click', function () {
  _insertAtCaret($('#transcription-page-wikitext'), "<del> </del>");
});

$('#strike').on('click', function () {
  _insertAtCaret($('#transcription-page-wikitext'), "{{Paul}}");
});

function _insertAtCaret(element, text) {
  var caretPos = element[0].selectionStart,
      currentValue = element.val();

  element.val(currentValue.substring(0, caretPos) + text + currentValue.substring(caretPos));
return false;
}

})

and the html is

 <div>
      <!-- editor buttons -->
      <p>
        <button id ="bold" class="btn btn-small btn-info" type="button">Bold</button>
        <button id ="italic" class="btn btn-small btn-info" type="button">Italic</button>
        <button id ="strike" class="btn btn-small btn-info" type="button">Strikeout</button>
      </p>
      <!-- text area -->
      <textarea name="transcription-page-wikitext" id="transcription-page-wikitext" cols="76" rows="16">some text</textarea>        
</div>

How can I change the function to ideally wrap or replace highlighted text, rather than just inserting at the cursor position?

Paul M
  • 3,937
  • 9
  • 45
  • 53
  • I don't see a question here. – egrunin May 12 '15 at 14:46
  • my function works great for simply inserting text at the cursor position. If the user had selected text though, it wouldnt replace (or ideally wrap) that text as most text editors work – Paul M May 12 '15 at 14:51

1 Answers1

1

Use the textarea's selectionEnd property as well as selectionStart and simple string manipulation.

Demo: http://jsfiddle.net/gffeab94/4/

Code:

function _insertAtCaret(element, text, textBefore, textAfter) {
    var el = element[0];
    var start = el.selectionStart;
    var end = el.selectionEnd;
    var newStart = start;
    var newEnd = end;
    var val = el.value;
    var beforeSel = val.slice(0, start);
    var afterSel = val.slice(end);
    if (start == end) {
        el.value = beforeSel + text + afterSel;
        newEnd += text.length;
    } else {
        el.value = beforeSel + textBefore + val.slice(start, end) +
                   textAfter + afterSel;
        newStart += textBefore.length;
        newEnd = newStart + end - start;
    }
    el.setSelectionRange(newStart, newEnd);
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536