Search code examples
javascriptjqueryselection-api

Get all text before SelectionStart and after SelectionEnd


I am creating a text editor from scratch.

code for getting bold

$('#bold').click(function(){

            var start = window.getSelection().toString();

            var bolded = '<b>' + start + '</b>';
            var cursorPositionBegin = $('#TextEditor').prop("selectionStart");
            var cursorPositionEnd = $('#TextEditor').prop("selectionEnd");
// to check 
                alert(bolded);
            })  

HTML CODE

<table width="50%">
    <tr>
        <td>
            <div>
                <div>
                    <span><input type=button value="B" id="bold"></span>
                </div>
                <div contenteditable="true">
                    <textarea cols="47" rows="23" placeholder="editor" id="TextEditor"></textarea>
                </div>
            </div>  
        </td>
    </tr>
</table>

When I click #bold for a selected set of characters I want to add characters in the #TextEditor. I thought maybe getting the beginning and ending position of cursor could help break up and join the begin and end together along with the characters to form what I require.

I also use jQuery

[update 1] Or is there an alternate method to do what I require? [update 2] added contenteditable="true" to div where #TextEditor id placed

Your help would be appreciated.


Solution

  • As @weBBer said you will not allowed to add tag inside textarea element use div with attribute contenteditable="true" instead

    $('#bold').click(function(){
      var string = window.getSelection().toString();
      var bolded = '<b>' + string + '</b>';
      var selC, range;
          if (window.getSelection) {
              selC = window.getSelection();
              if (selC.rangeCount) {
                  range = selC.getRangeAt(0);
                  range.deleteContents();
                  range.insertNode(document.createTextNode(bolded));
              }
          } else if (document.selection && document.selection.createRange) {
              range = document.selection.createRange();
              range.text = bolded;
          }
    }); 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table width="50%">
        <tr>
            <td>
                <div>
                    <div>
                        <span><input type=button value="B" id="bold"></span>
                    </div>
                    <div contenteditable="true" style="height: 300px;width: 300px;border: 1px solid black">
                        
                    </div>
                </div>  
            </td>
        </tr>
    </table>