April 14, 2012

How to set cursor at the end in a TEXTAREA? (by not using jQuery)

Question by Brian Hawk

Is there a way to set the cursor at the end in a TEXTAREA tag? I’m using Firefox 3.6 and I don’t need it to work in IE or Chrome. JavaScript is ok but it seems all the related answers in here use onfocus() event, which seems to be useless because when user clicks on anywhere within textarea, Firefox sets cursor position to there. I have a long text to display in a textarea so that it displays the last portion (making it easier to add something at the end).

Answer by Starx

Here is a function for that

function moveCaretToEnd(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}

[Demo][Source]

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!