-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
100 lines (71 loc) · 1.95 KB
/
index.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* Expsose `Switch`
*/
module.exports = Switch;
/**
* Accept one checkbox input field, and convert it into iOS style switch UI.
*/
function Switch(input) {
if ('checkbox' !== input.type) throw new Error('You can\'t make Switch out of non-checkbox input');
this.input = input;
this.input.style.display = 'none'; // hide the actual input
this.el = document.createElement('div');
this.el.className = 'ios-switch';
this._prepareDOM();
this.input.parentElement.insertBefore(this.el, this.input);
// read initial state and set Switch state accordingly
if (this.input.checked) this.turnOn()
}
/**
* Toggles on/off state
*/
Switch.prototype.toggle = function() {
if(this.el.classList.contains('on')){
this.turnOff();
} else {
this.turnOn();
}
this.triggerChange();
};
/**
* Turn on
*/
Switch.prototype.turnOn = function() {
this.el.classList.add('on');
this.el.classList.remove('off');
this.input.checked = true;
};
/**
* Turn off
*/
Switch.prototype.turnOff = function() {
this.el.classList.remove('on');
this.el.classList.add('off');
this.input.checked = false;
}
/**
* Triggers DOM event programatically on the real input field
*/
Switch.prototype.triggerChange = function() {
if ("fireEvent" in this.input){
this.input.fireEvent("onchange");
} else {
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
this.input.dispatchEvent(evt);
}
};
/**
* We need to prepare some DOM elements
*/
Switch.prototype._prepareDOM = function() {
var onBackground = document.createElement('div');
onBackground.className = 'on-background background-fill';
var stateBackground = document.createElement('div');
stateBackground.className = 'state-background background-fill';
var handle = document.createElement('div');
handle.className = 'handle';
this.el.appendChild(onBackground);
this.el.appendChild(stateBackground);
this.el.appendChild(handle);
};