javascript - Determine when caret reaches the end of input box - Stack Overflow

I have found this question which provides a solution to pute the exact position of the caret in a text

I have found this question which provides a solution to pute 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?

I have found this question which provides a solution to pute 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?

Share Improve this question edited May 23, 2017 at 12:19 CommunityBot 11 silver badge asked Oct 2, 2011 at 17:06 RandomblueRandomblue 116k150 gold badges363 silver badges558 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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.

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

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/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;
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744759054a4592058.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信