blob: 80af9059c1e7ef6803dff2c999b55e8485da1332 (
plain)
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
|
window.onload = function() {
// Update ingredients amounts
let inputs = []
document.querySelectorAll('code').forEach(function (number) {
// Install input
const value = parseNumber(number.innerHTML)
number.innerHTML = `<input value="${formatNumber(1, value)}">`
// Push to inputs
const element = number.children[0]
inputs.push({ element, value })
// Adjust width to content
adjustInputWidthToContent(element)
element.addEventListener('input', function() {
// Parse modified input value
const n = parseNumber(element.value)
if (!isNaN(n)) {
// Find current factor
const currentInput = inputs.find(function (input) {
return input.element === element
})
const factor = n / currentInput.value
// Apply factor to other inputs
inputs.forEach(function (input) {
if (input.element !== currentInput.element) {
input.element.value = formatNumber(factor, input.value)
adjustInputWidthToContent(element)
adjustInputWidthToContent(input.element)
}
})
}
})
})
// Set up done marks for steps
document.querySelectorAll('ol > li').forEach(item => {
item.addEventListener('click', event => {
if (event.target.tagName !== 'INPUT') {
item.className = item.className ? '' : 'completed'
}
})
})
}
function parseNumber(value) {
return parseFloat(value.replace(',', '.')) || 0
}
function formatNumber(factor, value) {
if (factor === 1) {
return value.toString().split('.').join(',')
} else {
const n = factor * value
const xs = n.toString().split('.')
const p = precision(value) || 1
if (xs.length == 2) {
return `${xs[0]},${xs[1].slice(0, p)}`
} else {
return n
}
}
}
function precision(value) {
const xs = value.toString().split('.')
if (xs.length === 2) {
return xs[1].length
}
}
function adjustInputWidthToContent(element) {
if (element.value.length === 0) {
element.style['width'] = `1ch`
element.style['background-color'] = `red`
} else {
element.style['width'] = `${element.value.length}ch`
element.style['background-color'] = `transparent`
}
}
|