How to use jquery to insert a character at a specified position in a monospaced text area

I have a monospaced text area (unlike the stackexchange editor). When my user clicks, I need a character that is automatically displayed in the previous line using jQuery. I know what I need to use .click()to bind a function to this event, but the logic of the function eludes me.

Desired behavior ... user clicks on asterisk *

Here is some text in my editor.
When I double click at a position*
I want to insert a new line above, with a new character at the same position

The above text should be next after the function starts

Here is some text in my editor.
                                 *
When I double click at a position*
I want to insert a new blank line above, at the same position

What I tried:

I found a jQuery carriage plugin that has a function called caret()that I can find to find the position of the asterisk when I click (position 74).

<script src='jquery.caret.js'></script>

    $('textarea').click(function(e) {
      if (e.altKey){
        alert($("textarea").caret());
      }
    });

, . .

+4
2

- caret.js

$('textarea').dblclick(function(e){
    var text = this.value;
    var newLinePos = text.lastIndexOf('\n', this.selectionStart);
    var lineLength = this.selectionStart - newLinePos;
    var newString = '\n';
    for(var i=1; i < lineLength; ++i){
        newString += ' ';
    }
    newString += text.substr(this.selectionStart,this.selectionEnd-this.selectionStart);
    this.value = [text.slice(0, newLinePos), newString, text.slice(newLinePos)].join('');
});

. ' '.

, , , .

​​ .

if(newLinePos == -1){
    this.value = newString + '\n' + this.value;
} else {
    this.value = [text.slice(0, newLinePos), '\n'+newString, text.slice(newLinePos)].join('');
}

http://jsfiddle.net/daveSalomon/3dr8k539/4/

+3

, , - .

function getCaretPosition(text, totalOffset) {
  var line = 0, pos = 0;
  for (var i = 0; i < Math.min(totalOffset, text.length); i++) {
    if (text[i] === '\n') {
      line++;
      pos = 0;
    } else {
      pos++;
    }
  }

  return { row: line, col: pos };
}

var caretPosition = getCaretPosititon($("textarea").val(), $("textarea").caret());
0

All Articles