0

I have this portion of code in my javascript file

function insertRespuesta(id, attach)
{
    document.getElementById(attach).value += " #" + id + " ";
    document.getElementById(attach).focus();
}

My html file:

<textarea name="textoConversacion" id="textoConversacion" class="mensaje-mensajeria"></textarea>
<a href='#' class='decoracion-link' onClick="insertRespuesta('<?php echo $cada['contador']; ?>','textoConversacion');">#<?php echo $cada['contador']; ?></a>

So if I click the link it will be focused on the textarea but the textarea cursor will be in the last position I had, and I need to put in the last cursor character + 1.

I preffer not using jquery.

Alejandro L.
  • 1,066
  • 5
  • 17
  • 38

1 Answers1

2

From the linked answer which does not use jQuery:

function insertRespuesta(id, attach)
{
    var el = document.getElementById(attach)
    if(el != null)
    {
        el.value += " #" + id + " ";
        setCaretPosition(attach, el.value.length);
    }
}

function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        elem.focus();
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else if(elem.selectionStart) {
            elem.setSelectionRange(caretPos, caretPos);
        }
    }
}

Here is a working jsFiddle.

Community
  • 1
  • 1
Dave Rager
  • 8,002
  • 3
  • 33
  • 52
  • Thanks @DaveRager for the answer. It is very good, but for example, if I have not writen anything, the cursor will keep at the begining, http://jsfiddle.net/bHfvY/1/ - I'm doing this like a forum, if you click the post nº you'll get an automated quote, and normaly you will click before write anything in the textarea (or similar). – Alejandro L. Jul 01 '13 at 07:56
  • PS: I think I fixed like this: http://jsfiddle.net/bHfvY/3/ but I'm not sure because I never used those functions of javascript (like that function) so I'm not sure if in some condition it will fail, but thanks again. – Alejandro L. Jul 01 '13 at 08:00
  • @rokimoki So what you want is that the cursor be positioned _after_ the existing text and _before_ the inserted text? Like this: http://jsfiddle.net/bHfvY/4/ Your last fiddle was still moving the cursor to the end for my Firefox browser but it looked like this is what you were trying to do. If so, I'll update my answer. – Dave Rager Jul 01 '13 at 14:49
  • Some times I confuse the final/end of a cursor position, I want exactly and the last character of the textarea, considering after the `#id` addition. – Alejandro L. Jul 02 '13 at 11:28