forked from naeka/jquery-switchbutton
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.switchbutton.js
291 lines (232 loc) · 9.11 KB
/
jquery.switchbutton.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
/*
* jQuery switchbutton
*
* Based on work by tdreyno on iphone-style-checkboxes for events management
* (https://github.com/tdreyno/iphone-style-checkboxes)
*
* Copyright 2011, L.STEVENIN
* Released under the MIT license.
*
* Depends:
* jquery.ui.widget.js (jQuery UI Widget Factory - http://wiki.jqueryui.com/w/page/12138135/Widget%20factory)
* jquery.tmpl.js (jQuery Templates - http://api.jquery.com/category/plugins/templates/)
*/
(function($, switchbutton){
$.widget('switchbutton.switchbutton', {
options: {
classes: '',
duration: 200,
dragThreshold: 5,
autoResize: true,
labels: true,
checkedLabel: 'ON',
uncheckedLabel: 'OFF',
disabledClass: 'ui-switchbutton-disabled ui-state-disabled',
template: '<div class="ui-switchbutton ui-switchbutton-default ${classes} {{if !labels}}ui-switchbutton-no-labels{{/if}}" tabindex=0>' +
'<label class="ui-switchbutton-disabled">' +
'<span>{{if labels}}${uncheckedLabel}{{/if}}</span>' +
'</label>' +
'<label class="ui-switchbutton-enabled">' +
'<span>{{if labels}}${checkedLabel}{{/if}}</span>' +
'</label>' +
'<div class="ui-switchbutton-handle"></div>' +
'</div>'
},
_create: function() {
if(!this.element.is(':checkbox')) {
return;
}
this._wrapCheckboxInContainer();
this._attachEvents();
this._globalEvents();
this._disableTextSelection();
if(this.element.prop('checked')) {
this.$container.toggleClass('ui-state-active', this.element.prop('checked'));
}
if(this.options.autoResize) {
this._autoResize();
}
this._initialPosition();
},
_wrapCheckboxInContainer: function() {
this.$container = $.tmpl(this.options.template, this.options);
this.element.after(this.$container);
this.element.remove();
this.$container.append(this.element);
this.$disabledLabel = this.$container.children('.ui-switchbutton-disabled');
this.$disabledSpan = this.$disabledLabel.children('span');
this.$enabledLabel = this.$container.children('.ui-switchbutton-enabled');
this.$enabledSpan = this.$enabledLabel.children('span');
this.$handle = this.$container.children('.ui-switchbutton-handle');
},
_attachEvents: function() {
var obj = this;
this.$container
// Listen for keyboard events such as <space>, <left> and <right>
.bind('keydown', function(event){
//Ignore if a key combo was used
if(event.ctrlKey || event.altKey || event.metaKey || event.shiftKey){
return;
}
//Catch <space>, <left>, and <right>
if(event.keyCode == 32 || event.keyCode == 37 || event.keyCode == 39) event.preventDefault();
//Ignore if the element is disabled
if(obj.element.prop('disabled')) {
return;
}
//Determine if we're supposed to toggle
var checked = obj.element.prop('checked')
if(event.keyCode == 32 || (event.keyCode == 37 && checked) || (event.keyCode == 39 && !checked)) {
//Perform the toggle
var willChangeEvent = jQuery.Event('willChange');
obj.element.trigger(willChangeEvent);
if(willChangeEvent.isDefaultPrevented()) return;
checked = !checked;
obj.element.prop('checked', checked);
obj.$container.toggleClass('ui-state-active', checked);
obj.element.change();
obj.element.trigger('didChange');
}
})
// A mousedown anywhere in the control will start tracking for dragging
.bind('mousedown touchstart', function(event) {
event.preventDefault();
if(obj.element.prop('disabled')) { return; }
$(this).focus();
var x = event.pageX || event.originalEvent.changedTouches[0].pageX;
$[switchbutton].currentlyClicking = obj.$handle;
$[switchbutton].dragStartPosition = x;
$[switchbutton].handleLeftOffset = parseInt(obj.$handle.css('left'), 10) || 0;
$[switchbutton].dragStartedOn = obj.element;
})
// Utilize event bubbling to handle drag on any element beneath the container
.bind('iPhoneDrag', function(event, x) {
event.preventDefault();
if(obj.element.prop('disabled')) { return; }
if(obj.element != $[switchbutton].dragStartedOn) { return; }
var p = (x + $[switchbutton].handleLeftOffset - $[switchbutton].dragStartPosition) / obj.rightSide;
if(p < 0) { p = 0; }
if(p > 1) { p = 1; }
obj.$handle.css({ 'left': p * obj.rightSide });
obj.$enabledLabel.css({ 'width': p * obj.rightSide });
obj.$disabledSpan.css({ 'margin-right': -p * obj.rightSide });
obj.$enabledSpan.css({ 'margin-left': -(1 - p) * obj.rightSide });
})
// Utilize event bubbling to handle drag end on any element beneath the container
.bind('iPhoneDragEnd', function(event, x) {
if(obj.element.prop('disabled')) { return; }
var willChangeEvent = jQuery.Event('willChange');
obj.element.trigger(willChangeEvent);
if(willChangeEvent.isDefaultPrevented()) {
checked = obj.element.prop('checked');
}
else {
var checked;
if($[switchbutton].dragging) {
var p = (x - $[switchbutton].dragStartPosition) / obj.rightSide;
checked = (p < 0) ? Math.abs(p) < 0.5 : p >= 0.5;
}
else {
checked = !obj.element.prop('checked');
}
}
$[switchbutton].currentlyClicking = null;
$[switchbutton].dragging = null;
obj.element.prop('checked', checked);
obj.$container.toggleClass('ui-state-active', checked);
obj.element.change();
obj.element.trigger('didChange');
});
// Animate when we get a change event
this.element.change(function() {
obj.refresh();
var new_left = obj.element.prop('checked') ? obj.rightSide : 0;
obj.$handle.animate({ 'left': new_left }, obj.options.duration);
obj.$enabledLabel.animate({ 'width': new_left }, obj.options.duration);
obj.$disabledSpan.animate({ 'margin-right': -new_left }, obj.options.duration);
obj.$enabledSpan.animate({ 'margin-left': new_left - obj.rightSide }, obj.options.duration);
});
},
_globalEvents: function() {
if($[switchbutton].initComplete) {
return;
}
var opt = this.options;
$(document)
// As the mouse moves on the page, animate if we are in a drag state
.bind('mousemove touchmove', function(event) {
if(!$[switchbutton].currentlyClicking) { return; }
event.preventDefault();
var x = event.pageX || event.originalEvent.changedTouches[0].pageX;
if(!$[switchbutton].dragging && (Math.abs($[switchbutton].dragStartPosition - x) > opt.dragThreshold)) {
$[switchbutton].dragging = true;
}
$(event.target).trigger('iPhoneDrag', [x]);
})
// When the mouse comes up, leave drag state
.bind('mouseup touchend', function(event) {
if(!$[switchbutton].currentlyClicking) { return; }
event.preventDefault();
var x = event.pageX || event.originalEvent.changedTouches[0].pageX;
$($[switchbutton].currentlyClicking).trigger('iPhoneDragEnd', [x]);
});
},
_disableTextSelection: function() {
// Elements containing text should be unselectable
$([this.$handle, this.$disabledLabel, this.$enabledLabel, this.$container]).attr('unselectable', 'on');
},
_autoResize: function() {
var onLabelWidth = this.$enabledLabel.width(),
offLabelWidth = this.$disabledLabel.width();
//If width() return 0, then the min width of switch is maintained for default value.
if(offLabelWidth === 0) {
offLabelWidth = 32;
}
var spanPadding = this.$disabledSpan.innerWidth() - this.$disabledSpan.width(),
handleMargins = this.$handle.outerWidth() - this.$handle.innerWidth();
var containerWidth = handleWidth = (onLabelWidth > offLabelWidth) ? onLabelWidth : offLabelWidth;
this.$handle.css({ 'width': handleWidth });
handleWidth = this.$handle.width();
containerWidth += handleWidth + 6;
spanWidth = containerWidth - handleWidth - spanPadding - handleMargins;
this.$container.css({ 'width': containerWidth });
this.$container.find('span').width(spanWidth);
},
_initialPosition: function() {
this.$disabledLabel.css({ width: this.$container.width() - 5 });
this.rightSide = this.$container.width() - this.$handle.outerWidth();
if(this.element.prop('checked')) {
this.$handle.css({ 'left': this.rightSide });
this.$enabledLabel.css({ 'width': this.rightSide });
this.$disabledSpan.css({ 'margin-right': -this.rightSide });
}
else {
this.$enabledLabel.css({ 'width': 0 });
this.$enabledSpan.css({ 'margin-left': -this.rightSide });
}
this.refresh();
},
enable: function() {
this.element.prop('disabled', false);
this.refresh();
return this._setOption('disabled', false);
},
disable: function() {
this.element.prop('disabled', true);
this.refresh();
return this._setOption('disabled', true);
},
widget: function() {
return this.$container;
},
refresh: function() {
if(this.element.prop('disabled')) {
this.$container.addClass(this.options.disabledClass);
return false;
}
else {
this.$container.removeClass(this.options.disabledClass);
}
}
});
})(jQuery, 'switchbutton');