-
Notifications
You must be signed in to change notification settings - Fork 0
/
gridnav.js
79 lines (77 loc) · 2.2 KB
/
gridnav.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
Gridnav - a way to navigate lists with a keyboard in a
2D fashion instea of item-by-item
Copyright (c) 2016 Christian Heilmann
Licensed under the MIT license:
http://www.opensource.org/licenses/mit-license.php
Version: 1.0.0
*/
var Gridnav = function (listelement) {
var that = this;
this.list = (typeof listelement) === 'string' ?
document.querySelector(listelement) :
listelement;
if (!this.list) {
throw Error('List item could not be found');
}
this.setcodes = function (amount) {
that.codes = {
39:1, 68:1,
65:-1, 37:-1,
87:-that.amount, 38:-that.amount,
83: that.amount, 40:that.amount
};
}
if (!this.list.getAttribute('data-element')) {
this.element = this.list.firstElementChild.firstElementChild.tagName;
} else {
this.element = this.list.getAttribute('data-element').toUpperCase();
}
if (!this.list.getAttribute('data-amount')) {
this.amount = 6502;
this.setcodes(this.amount);
} else {
this.amount = +this.list.getAttribute('data-amount');
this.setcodes(this.amount);
}
this.setcodes(this.amount);
this.all = this.list.querySelectorAll(this.element);
this.keynav = function(ev) {
var t = ev.target;
var c;
var posx, posy;
if (t.tagName === that.element) {
for (var i = 0; i < that.all.length; i++) {
if (that.all[i] === t) {
c = i;
posx = that.all[c].offsetLeft;
posy = that.all[c].offsetTop;
break;
}
}
if (that.codes[ev.keyCode]) {
var kc = that.codes[ev.keyCode];
if (kc > -6502 && kc < 6502) {
if (that.all[c + kc]) {
that.all[c + kc].focus();
}
} else {
var add = kc < 0 ? -1 : 1;
while (that.all[i]) {
if (that.all[i].offsetLeft === posx &&
that.all[i].offsetTop !== posy) {
that.all[i].focus();
break;
}
i += add;
}
}
}
}
}
this.list.addEventListener('keyup', this.keynav);
};
Gridnav.lists = [];
[].forEach.call(document.querySelectorAll('.gridnav'), function (item, key) {
Gridnav.lists[key] = new Gridnav(item);
});