-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.toggler.js
78 lines (61 loc) · 1.62 KB
/
jquery.toggler.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
(function ($) {
$.fn.toggler = function (opts) {
// Extend default options
var options = $.extend({}, $.fn.toggler.defaults, opts);
return this.each(function () {
var elem = $(this);
var toggle = elem;
var input = null;
var currentState = 0;
if(elem[0].localName == "input")
{
elem.hide();
toggle = $('<a href="#"></a>');
elem.after(toggle);
input = elem;
}
if(opts && !opts.states && opts.positiveState) {
$.extend(options.states[0], opts.positiveState);
}
if(opts && !opts.states && opts.negativeState) {
$.extend(options.states[1], opts.negativeState);
}
toggle.addClass(options.class);
//pick the first state and apply it
toggleState(toggle, input, options.states[0], null);
//apply events
toggle.click(function(e) {
e.preventDefault();
var newState = (currentState + 1) % options.states.length;
toggleState(toggle, input, options.states[newState], options.states[currentState]);
currentState = newState;
});
});
};
function toggleState(elem, input, newState, oldState) {
if(newState.text != null)
{
elem.text(newState.text);
}
elem.data('toggle-state', newState.value);
if(input != null) {
input.val(newState.value);
}
if(oldState != null && oldState.class != null) {
elem.removeClass(oldState.class);
}
if(newState.class != null) {
elem.addClass(newState.class);
}
}
// # default options
//
//
$.fn.toggler.defaults = {
class: "button",
states: [
{ text: "Yes", value: true, class: "positive"},
{ text: "No", value: false, class: "negative"}
]
};
})(jQuery);