-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
58 lines (57 loc) · 2.36 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
const billInput = document.getElementById("bill");
const tipButtons = document.querySelectorAll(".button-container button, .button-container input");
const numberOfPeopleInput = document.getElementById("people");
const tipOutput = document.getElementById("tipAmountPerPerson");
const totalOutput = document.getElementById("totalAmountPerPerson");
const resetButton = document.getElementById("resetButton");
const tips = [5, 10, 15, 25, 50];
let currentTip = 0, activeButton;
function calculateTipAndTotalPerPerson(bill, tip, people) {
tip = Number(tip);
return [bill * tip / 100 / people, bill * (tip + 100) / 100 / people];
}
function updateValues() {
let tipPerPerson = calculateTipAndTotalPerPerson(billInput.value, currentTip, numberOfPeopleInput.value)[0].toFixed(2).toString();
let totalPerPerson = calculateTipAndTotalPerPerson(billInput.value, currentTip, numberOfPeopleInput.value)[1].toFixed(2).toString();
console.log(totalPerPerson);
tipPerPerson = isFinite(tipPerPerson) ? tipPerPerson : "0.00";
totalPerPerson = isFinite(totalPerPerson) ? totalPerPerson : "0.00";
tipOutput.innerText = "$" + tipPerPerson;
totalOutput.innerText = "$" + totalPerPerson;
if (totalOutput.innerText === "$0.00") {
resetButton.setAttribute("emptyState", "");
} else {
try {resetButton.removeAttribute("emptyState")} catch (e) {};
}
}
numberOfPeopleInput.addEventListener("keyup", () => {
updateValues();
});
billInput.addEventListener("keyup", () => {
updateValues();
});
resetButton.addEventListener("click", () => {
billInput.value = "";
numberOfPeopleInput.value = "";
updateValues();
resetButton.setAttribute("emptyState", "");
});
tipButtons.forEach(button => {
if (Array.from(tipButtons).indexOf(button) <= 4) {
button.addEventListener("click", () => {
try { activeButton.removeAttribute("selected")} catch (e) {};
activeButton = button;
button.setAttribute("selected", "");
currentTip = tips[Array.from(tipButtons).indexOf(button)];
tipButtons[5].value = "";
updateValues();
});
} else {
button.addEventListener("keyup", () => {
try { activeButton.removeAttribute("selected") } catch (e) { };
activeButton = undefined;
currentTip = button.value;
updateValues();
})
}
});