-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathsavy.js
executable file
·84 lines (75 loc) · 2.86 KB
/
savy.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
(function($) {
$.fn.savy = function(order, fn) {
const sv = "savy-";
if (order == "load") {
$(this).each(function() {
if ($(this).is(":radio")) {
if (localStorage.getItem(sv + $(this).attr("name"))) {
if (localStorage.getItem(sv + $(this).attr("name")) == this.id) {
this.checked = true;
} else {
this.checked = false;
}
}
$(this).change(function() {
localStorage.setItem(sv + $(this).attr("name"), this.id);
});
} else if ($(this).is(":checkbox")) {
if (localStorage.getItem(sv + this.id)) {
this.checked = (localStorage.getItem(sv + this.id) == "1" ? true : false);
}
$(this).change(function() {
localStorage.setItem(sv + this.id, (this.checked ? "1" : "0"));
});
} else if ($(this).is("input") || $(this).is("textarea")) {
if (localStorage.getItem(sv + this.id)) {
this.value = localStorage.getItem(sv + this.id);
}
$(this).on('focus', function() {
var intervalDuration = 500,
interval = setInterval(() => {
localStorage.setItem(sv + this.id, this.value);
if (!$(this).is(":focus")) clearInterval(interval);
}, intervalDuration);
});
} else if ($(this).is("select")) {
if ($(this).is("[multiple]")) {
if (localStorage.getItem(sv + this.id)) {
$(this).val(localStorage.getItem(sv + this.id).split(","));
} else {
localStorage.setItem(sv + this.id, $(this).val());
}
$(this).change(function() {
localStorage.setItem(sv + this.id, $(this).val());
});
} else {
if (localStorage.getItem(sv + this.id)) {
$(this).val(localStorage.getItem(sv + this.id));
} else {
localStorage.setItem(sv + this.id, $(this).val());
}
$(this).change(function() {
localStorage.setItem(sv + this.id, $(this).val());
});
}
}
});
if ($.isFunction(fn)) { fn(); }
} else if (order == "destroy") {
$(this).each(function() {
if ($(this).is(":radio")) {
if (localStorage.getItem(sv + $(this).attr("name"))) {
localStorage.removeItem(sv + $(this).attr("name"));
}
} else {
if (localStorage.getItem(sv + this.id)) {
localStorage.removeItem(sv + this.id);
}
}
});
if ($.isFunction(fn)) { fn(); }
} else {
console.error("savy action not defined. Please use $('.classname').savy('load') to trigger savy to save all inputs");
}
};
})(jQuery);