Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine when caret reaches the end of input box

Tags:

javascript

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?

like image 515
Randomblue Avatar asked Dec 11 '25 15:12

Randomblue


2 Answers

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.

like image 144
Rob W Avatar answered Dec 14 '25 07:12

Rob W


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

like image 44
Some Guy Avatar answered Dec 14 '25 05:12

Some Guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!