-
Notifications
You must be signed in to change notification settings - Fork 253
/
buttons.js
59 lines (44 loc) · 1.64 KB
/
buttons.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
var Buttons = (function () {
'use strict';
var Buttons = function (element, buttonNames, initialActiveIndex, changeCallback) {
var elements = [];
for (var i = 0; i < buttonNames.length; ++i) {
var button = document.createElement('div');
button.innerHTML = buttonNames[i];
element.appendChild(button);
elements.push(button);
}
var activeElement = elements[initialActiveIndex];
var refresh = function () {
for (var i = 0; i < elements.length; ++i) {
if (elements[i] === activeElement) {
elements[i].className = 'button-selected';
} else {
elements[i].className = 'button-unselected';
}
}
};
for (var i = 0; i < elements.length; ++i) {
(function () { //create closure to store index
var index = i;
var clickedElement = elements[i];
var onSelect = function (event) {
event.preventDefault();
if (activeElement !== clickedElement) {
activeElement = clickedElement;
changeCallback(index);
refresh();
}
};
elements[i].addEventListener('click', onSelect);
elements[i].addEventListener('touchstart', onSelect);
}());
}
this.setIndex = function (index) {
activeElement = elements[index];
refresh();
};
refresh();
};
return Buttons;
}());