Search code examples
javascriptfocushyperlinkcursor-position

Focus on a textarea to the last + 1 character cursor, javascript


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.


Solution

  • 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.