Move cursor to the end of input [JavaScript]

Alvaro Trigo Avatar

Follow on Twitter

You can move the cursor to the end of an input or a textarea by using selectionStart and selectionEnd properties of input elements using JavaScript.

These kind of things might seem simple but can be a bit tricky. So let’s clear this out and see what’s the best way of achieving this.

This can be done with both jQuery or JavaScript, but there’s very little difference between the two so I usually recommend making use of JavaScript.

Using JavaScript

This way is very similar to the previous one using jQuery but using sectionEnd and sectionStart properties of the input.

function moveCursorToEnd(e) {
    setTimeout(function(){
        const input = document.querySelector('#my-input');
        input.selectionStart = input.selectionEnd = input.value.length;
        input.focus();
    }, 0)
}

document.querySelector('#move').addEventListener('click', moveCursorToEnd);
Code language: JavaScript (javascript)

Notice that we are also using setTimeout. The reason for it is that Chrome has some bug which causes the focus event to get fired before the cursor is moved into the input.

Move cursor to the end on focus

Now, what if we want the cursor to move to the end whenever we focus the input?

We will still apply the same function but instead of having a click event we will trigger it when the input gets focused.

document.querySelector('#my-input').addEventListener('focus', moveCursorToEnd);
Code language: JavaScript (javascript)

Here’s a demo:

And if you prefer a more simple solution for these cases, here’s another approach you can use:

<input id="my-input" type="text" value="testvalue" onfocus="this.value = this.value;" name="test"/>
Code language: HTML, XML (xml)

Using jQuery

In this case we will be using another approach by just using focus and val. This is what we’ll do:

    1. Read the value of the input
    1. Remove the input’s value.
    1. Blur the input.
    1. Focus the input.
    1. Set the value again.
function moveCursorToEnd(e) {
    const input = $('#my-input');
    const originalValue = input.val();
    input.val('');
    input.blur().focus().val(originalValue);
}

$('#move').click(moveCursorToEnd);

Here’s an example:

Was this page helpful?