3

I have found this question which provides a solution to compute the exact position of the caret in a text or input box.

For my purposes, this is overkill. I only want to know when the caret is at the end of all the text of an input box. Is there an easy way to do that?

Community
  • 1
  • 1
Randomblue
  • 112,777
  • 145
  • 353
  • 547

3 Answers3

5

In all modern browsers:

//input refers to the text box
if(input.value.length == input.selectionEnd){
    //Caret at end.
}

The selectionEnd property of an input element equals the highest selection index.

Rob W
  • 341,306
  • 83
  • 791
  • 678
2
<script>
input = document.getElementById('yourinputfieldsid');
if(input.selectionEnd == input.selectionStart && input.value.length == input.selectionEnd){
//your stuff
}
</script>

This checks to see if the caret actually is at the end, and makes sure that it isn't only because of the selection that it shows an end value.

Some Guy
  • 15,854
  • 10
  • 58
  • 67
2

You don't specify what you want to happen when some text is selected, so in that case my code just checks whether the end of the selection is at the end of the input.

Here's a cross-browser function that wil work in IE < 9 (which other answers will not: IE only got selectionStart and selectionEnd in version 9).

Live demo: http://jsfiddle.net/vkCpH/1/

Code:

function isCaretAtTheEnd(el) {
    var valueLength = el.value.length;
    if (typeof el.selectionEnd == "number") {
        // Modern browsers
        return el.selectionEnd == valueLength;
    } else if (document.selection) {
        // IE < 9
        var selRange = document.selection.createRange();
        if (selRange && selRange.parentElement() == el) {
            // Create a working TextRange that lives only in the input
            var range = el.createTextRange();
            range.moveToBookmark(selRange.getBookmark());
            return range.moveEnd("character", valueLength) == 0;
        }
    }
    return false;
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536