Arrow Key Navigation for Text Fields

Here is a class for enabling the use of arrow keys to navigate through a grid of input fields: (using mootools)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
var FocusMover = new Class({

        initialize: function(sel, col_num){

                this.sel = sel
                this.col_num = col_num
                this.inputs = $$(this.sel)
                this.current_focus = 0

                var self = this

                this.inputs.each(function(item, index){
                        item.addEvent('keydown',function(key){
                                $try(function(){
                                        self[key.key]()
                                })
                        })
                        item.addEvent('focus',function(e){
                                self.refresh(e)
                        })

                        item.set('myid', index)
                })

                this.inputs[0].focus()

        },


        refresh: function(e){
                this.current_focus = e.target.get('myid')
        },

        down: function(){
                i = parseInt(this.current_focus) + parseInt(this.col_num)
                this.inputs[i].focus()
        },

        up: function(){
                i = parseInt(this.current_focus) - parseInt(this.col_num)
                this.inputs[i].focus()
        },

        left: function(){
                i = parseInt(this.current_focus) - 1
                this.inputs[i].focus()
        },

        right: function(){
                i = parseInt(this.current_focus) + 1
                this.inputs[i].focus()
        }

})

As you can see, the constructor takes two arguments: a selector (which should return a list of all your input fields), and the number of input field columns. So for a 4x2 table, you would set it up like this:

1
var FM = new FocusMover('#mytable input', 4)