Table内で、方向キー(矢印キー)でセル移動

tableにフォーカスがあるとき、方向キー(矢印キー)でTD要素のフォーカスを上下左右の隣接TD要素に移動するようにした。

 準備として、あらかじめ、TD要素の中に置く、実際にフォーカスが当たる要素にID属性を下記のように付けておく。id='mj_search_results_?_?'(前の桁は行番号、後ろの桁は列番号。今回は1行目や1列目を0とした。)

 

以下、coffeescript

 

#今回の処理を実装する関数定義
tableElementFocusController=(ev) ->

 #mj_list_tableのtd要素(id=mj_search_results_?_?)にフォーカスがあるときに
  #矢印キーのキーイベントがあったら、表内のセルをフォーカス移動する。
  if ev.target.id.match(/^mj_search_results_(\d+)_(\d+)$/)

   now_row=parseInt(RegExp.$1)
   now_col=parseInt(RegExp.$2)

    id_header="#mj_search_results_"
    #現在フォーカスの当たっているセルの上下左右隣のセルを特定する。
    #次行の先頭セル、前行の最終セルも特定しておく。
    #本当は押した方向キーに関係するセルだけ特定すればよいが、わかりやすいし特に遅くないのでこれで良しとした。
    cell_left   =id_header+now_row+"_"+(now_col-1)
    cell_right  =id_header+now_row+"_"+(now_col+1)
    cell_up     =id_header+(now_row-1)+"_"+now_col
    cell_down   =id_header+(now_row+1)+"_"+now_col
    cell_first_of_next_line=id_header+(now_row+1)+"_0"
    cell_last_of_prev_line =id_header+(now_row-1)+"_9"

    #左方向キーはキーコード 37
    if ev.keyCode==37
      if $(cell_left).length
        $(cell_left)[0].focus()
      else if $(cell_left).length==0 && $(cell_last_of_prev_line).length
        $(cell_last_of_prev_line)[0].focus()
      else
        #none.
      ev.preventDefault()
      ev.stopPropagation()

    #右方向キーはキーコード 39
    else if ev.keyCode==39
      if $(cell_right).length
        $(cell_right)[0].focus()
      else if $(cell_right).length==0 && $(cell_first_of_next_line).length
        $(cell_first_of_next_line)[0].focus()
      else
        #none.
      ev.preventDefault()
      ev.stopPropagation()
    
    #上方向キーはキーコード 38
    else if ev.keyCode==38
      if $(cell_up).length
        $(cell_up)[0].focus()
      else
        #none.
      ev.preventDefault()
      ev.stopPropagation()

    #下方向キーはキーコード 40
    else if ev.keyCode==40
      if $(cell_down).length
        $(cell_down)[0].focus()
      else
        #none.
      ev.preventDefault()
      ev.stopPropagation()
#今回はdocumentにイベント登録した。
$(document).keydown (e) ->
  tableElementFocusController(e)