0

I am having hard time navigating from one element to another using keyboard arrow; I want the navigation to occur only when cursor is at the start or end of the text i.e. "move to right only if at the end of the text and move to left only at the start of the text, say I press left arrow when at the end of the text I do not want to navigate, I simply want to let the default event happen."

Here's a start of what i want, Try1

this is the function I need help writing

function isEndOrStartOfText($this)
{
    return true;
    // @todo calculate here
}  
ro ko
  • 2,906
  • 3
  • 37
  • 58
  • 2
    This answer contains information on how to get the current cursor position inside a text field - [Get Cursor Position within a Text Input field](http://stackoverflow.com/questions/2897155/get-cursor-position-within-a-text-input-field) – CodingIntrigue Jan 31 '14 at 15:03

2 Answers2

1

You want to separate those 2 checks because you can be at the end of the string and press left, it shouldn't focus the previous field.

In modern browsers you can get node.selectionStart on the node, then you check on the left-key press if the selection start is 0:

if ($this[0].selectionStart === 0) {
    e.preventDefault();
    if ($('#'+previous_id).length > 0) {
        $('#'+previous_id).focus();
    }
}

For the right key, you do that check:

if ($this[0].selectionStart === $this.val().length) {
    e.preventDefault();
    if ($('#'+next_id).length > 0) {
        $('#'+next_id).focus();
    }
}

I updated your example: http://jsfiddle.net/88VL8/7/ (tested in Chrome)

PS: This code will not work on IE, there's a polyfill available here on stackOverflow, just search for "How to get caret position in textarea?"

Yulian
  • 318
  • 2
  • 8
1

Using the answer to the question that RGraham suggested, I modified my code a bit to get the expected result

function getCursorPosition(jqueryItem) {
   var input = jqueryItem.get(0);
   if (!input) return; // No (input) element found
   if ('selectionStart' in input) {
    // Standard-compliant browsers
    return input.selectionStart;
   } else if (document.selection) {
    // IE
    input.focus();
    var sel = document.selection.createRange();
    var selLen = document.selection.createRange().text.length;
    sel.moveStart('character', -input.value.length);
    $("#sel").html(sel);
    $("#selLen").html(selLen);
    return sel.text.length - selLen;
   }
}
Community
  • 1
  • 1
ro ko
  • 2,906
  • 3
  • 37
  • 58