Search code examples
javascriptjquerypositiontextarea

How to remember a position in a texarea?


I just want to remember always the last position in a textarea, but I fail always.

I've got this code:

//This function catch the position

(function ($, undefined) {
    $.fn.getCursorPosition = function() {
        var el = $(this).get(0);
        var pos = 0;
        if('selectionStart' in el) {
            pos = el.selectionStart;
        } else if('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);

    //Insert the text by clicking an icon

function insertar(texto) {

  var div = $('textarea');     
  var text = div.val();
  var pos = div.getCursorPosition();
  text = text.substring(0,pos) + " " + texto + text.substring(pos);
  div.val(text);

}

$('#icon').click(function(evt){ insertar(':icon:'); });

Well, if I write this:

"hello hello"

And I want to add this with the function:

"hi hi hello hello"

It give me this:

"hi hello hello hi."

I think the second time I execute the function, this forget the position and add the text at the end of the text.

PD: I'm adding text clicking on an image. I'm trying to do a quick reply fieldset for a forum.

Anyone knows where the problem is?

Here is my demo where you can see it: http://jsfiddle.net/ko295zpw/6/


Solution

  • One option would be to set a bool that determines whether or not you need to re-find the cursor position, then reset the bool to true every time the textarea is clicked and set it to false after you've found the position the first time after the user has clicked on the textarea. You'd need to move the declarations of both var pos and the bool to a scope outside the insertar function. So:

    var encontrarPos = true;
    var pos = 0;
    function insertar(texto) {
    
        var div = $('textarea');     
        var text = div.val();
        if (encontrarPos) pos = div.getCursorPosition();
        encontrarPos = false;
        console.log(pos);
        text = text.substring(0,pos) + texto + " " + text.substring(pos);
        div.val(text);
    
    }
    
    $('textarea').click(function() {
        encontrarPos = true;
    });
    

    And here's the updated Fiddle