Search code examples
jqueryinputkeyeventindexofarrow-keys

How to know at which position the blinking pipe character is in a string?


I would like to know if there are possible to know at which position of the input value is at when pressing a key.

Say I have a text field.

<input id="name" type="text">

And I want to to something if the right-arrow-key is pressed only if they are at the end of the string, and I want something else if the left-arrow-key is pressed if they are at the beginning of the input value. I want to be able to something like this:

$("#name").keyup( function(e) {
    if( e.which === 37 ) { // left
         if( isAtBeginningOfInputValue ) {
             // Do something
         }
    } else if( e.which === 39 ) { // right
         if( isAtEndOfInputValue ) {
             // Do something else
         }
    }
});

Is this possible?


Solution

  • the correct term for this blinking thin is caret

    here you have a get function for textarea-elements

    function GetCaretPosition (ctrl) {
    
        var CaretPos = 0;  
        // IE Support
    
        if (document.selection) {
    
        ctrl.focus ();
    
        var Sel = document.selection.createRange ();
    
        Sel.moveStart ('character', -ctrl.value.length);
    
        CaretPos = Sel.text.length;
    
        }
    
        // Firefox support
    
        else if (ctrl.selectionStart || ctrl.selectionStart == '0')
    
        CaretPos = ctrl.selectionStart;
    
        return (CaretPos);
    
    }