1

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?

Erik
  • 14,060
  • 49
  • 132
  • 218
  • possible duplicate of [Caret position in textarea, in characters from the start](http://stackoverflow.com/questions/263743/caret-position-in-textarea-in-characters-from-the-start) – Kyle Needham Apr 26 '14 at 16:02
  • There's no caret in your example. Possibly you are referring to the pipe? In addition, I'm not sure about 2013, but for prior versions of Excel, the cell (or range object), does not have a keydown event. Those events only applied to forms and form controls. – Ron Rosenfeld Apr 26 '14 at 16:05
  • Did you mean like this? http://jsfiddle.net/8Ayrd/32/ – dsgriffin Apr 26 '14 at 16:11
  • Yes that is it! Is it cross browser way? – Erik Apr 26 '14 at 16:24
  • And how could I make this approach to determine cell switching for left keyboard key? – Erik Apr 26 '14 at 16:30
  • @Erik It works for IE9+, and could you show me an example of 'cell switching'? I don't know anything about excel or what you're doing really – dsgriffin Apr 26 '14 at 16:36
  • @Erik Glad to help, sorry about not being able to help with the cell switching part, I've posted it as an answer anyhow – dsgriffin Apr 26 '14 at 17:00

1 Answers1

0

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.

Community
  • 1
  • 1
dsgriffin
  • 66,495
  • 17
  • 137
  • 137