-
Notifications
You must be signed in to change notification settings - Fork 0
/
radiogroup.js
71 lines (51 loc) · 1.59 KB
/
radiogroup.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
(function() {
'use strict';
// Define values for keycodes
var VK_ENTER = 13;
var VK_SPACE = 32;
var VK_LEFT = 37;
var VK_UP = 38;
var VK_RIGHT = 39;
var VK_DOWN = 40;
// Helper function to convert NodeLists to Arrays
function slice(nodes) {
return Array.prototype.slice.call(nodes);
}
function RadioGroup(id) {
this.el = document.querySelector(id);
this.buttons = slice(this.el.querySelectorAll('.radio'));
this.focusedIdx = 0;
this.focusedButton = this.buttons[this.focusedIdx];
this.el.addEventListener('keydown', this.handleKeyDown.bind(this));
}
RadioGroup.prototype.handleKeyDown = function(e) {
switch(e.keyCode) {
case VK_UP:
case VK_LEFT: {
e.preventDefault();
// This seems like a good place to do some stuff :)
alert("up pushed");
break;
}
case VK_DOWN:
case VK_RIGHT: {
e.preventDefault();
// This seems like a good place to do some stuff :)
alert("down pushed");
break;
}
}
this.changeFocus(this.focusedIdx); // <-- Hmm, interesting...
};
RadioGroup.prototype.changeFocus = function(idx) {
// Set the old button to tabindex -1
this.focusedButton.tabIndex = -1;
this.focusedButton.removeAttribute('checked');
// Set the new button to tabindex 0 and focus it
this.focusedButton = this.buttons[idx];
this.focusedButton.tabIndex = 0;
this.focusedButton.focus();
this.focusedButton.setAttribute('checked', 'checked');
};
var group1 = new RadioGroup('#group1');
}());