Frage

I have an editable table like excel one and I'm making keydown handling for switching to next cell.

Let's say I have the following cell with caret highlited:

This is a text|

In the example above the caret resides at last character so if an user press right key on the keyboard I need to switch cell editor to next cell.

My question is how do I know that caret is resides at last character in textarea in keydown event handler?

War es hilfreich?

Lösung

As you're always going to be checking for the last character, you could grab the length property of the textarea value on every keydown and compare the length with the textarea's selectionEnd property:

selectionEnd - Specifies or returns the end position of the selected text within the current element.

Example:

document.getElementById("textAreaIdHere").onkeydown = function(){
  // Get length of textarea value
  var len = this.value.length;
  // If character entered is at the end of the textarea (therefore cursor)
  if(this.selectionEnd === len) {
    // Is at the end
  }   
}

jsFiddle here


selectionEnd is only available to use as of IE9+. For implementing this feature in older browsers, this shim may be of use.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top