-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
62 lines (47 loc) · 1.47 KB
/
main.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
var CUP_VOLUME_ML = 150
var FADE_DURATION_MS = 200
function find(xs, f) {
return Array.prototype.find.call(xs, f);
}
function isChecked(n) {
return n.checked;
}
function getIntValue(n) {
return parseInt(n.value, 10);
}
var fadeTimers = {};
function updateFade(elem, value, ms) {
if (elem.value === "") {
elem.value = value;
return;
}
if (fadeTimers[elem.id])
clearTimeout(fadeTimers[elem.id]);
elem.style.opacity = 0;
fadeTimers[elem.id] = setTimeout(function () {
elem.value = value;
elem.style.opacity = 1;
fadeTimers[elem.id] = null;
}, ms);
}
function updateNumbers() {
var servingsIn = document.getElementsByName("servingsIn");
var ratioIn = document.getElementsByName("ratioIn");
var volumeOut = document.getElementById("volumeOut");
var gramsOut = document.getElementById("gramsOut");
var servings = getIntValue(find(servingsIn, isChecked));
var ratio = 1 / getIntValue(find(ratioIn, isChecked));
var volume = servings * CUP_VOLUME_ML;
var grams = volume * ratio;
var displayVolume = volume.toFixed(0).toString();
if (volumeOut.value !== displayVolume)
updateFade(volumeOut, displayVolume, FADE_DURATION_MS);
var displayGrams = grams.toFixed(0).toString();
if (gramsOut.value !== displayGrams)
updateFade(gramsOut, displayGrams, FADE_DURATION_MS);
}
window.onload = function () {
var settingsForm = document.getElementById("settingsForm");
settingsForm.onchange = updateNumbers;
updateNumbers();
};