-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
91 lines (82 loc) · 2.59 KB
/
script.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
85
86
87
88
89
90
91
const tipPercentButtons = document.querySelectorAll(".tip-percent-btn");
const tipInput = document.getElementById("tipInput");
const resetBtn = document.getElementById("resetBtn");
const allInputs = document.querySelectorAll("input");
const billInput = document.getElementById("bill");
const peopleInput = document.getElementById("people");
const tipPerPersonSpan = document.getElementById("tipPerPerson");
const billPerPersonSpan = document.getElementById("billPerPerson");
let tipPercent = 0;
let bill = 0;
let people = 0;
tipPercentButtons.forEach((tipPercentButton) => {
tipPercentButton.addEventListener("click", (e) => {
e.preventDefault();
tipInput.value = "";
tipPercentButtons.forEach((btn) => {
btn.classList.remove("tip-percent-btn-active");
});
tipPercentButton.classList.add("tip-percent-btn-active");
tipPercent = parseFloat(tipPercentButton.value);
calculateBillAndTip();
});
});
tipInput.addEventListener("focus", () => {
tipPercentButtons.forEach((button) => {
button.classList.remove("tip-percent-btn-active");
});
});
tipInput.addEventListener("input", () => {
tipPercent = parseFloat(tipInput.value) || 0;
calculateBillAndTip();
});
allInputs.forEach((input) => {
input.addEventListener("input", () => {
if (resetBtn.classList.contains("inactiveResetBtn")) {
resetBtn.classList.remove("inactiveResetBtn");
resetBtn.classList.add("activeResetBtn");
}
calculateBillAndTip();
});
});
resetBtn.addEventListener("click", () => {
allInputs.forEach((input) => {
input.value = "";
});
tipPercentButtons.forEach((btn) => {
btn.classList.remove("tip-percent-btn-active");
});
tipPercent = 0;
bill = 0;
people = 0;
tipPerPersonSpan.innerHTML = "0.00";
billPerPersonSpan.innerHTML = "0.00";
resetBtn.classList.remove("activeResetBtn");
resetBtn.classList.add("inactiveResetBtn");
});
billInput.addEventListener("input", () => {
bill = parseFloat(billInput.value) || 0;
calculateBillAndTip();
});
peopleInput.addEventListener("input", () => {
people = parseInt(peopleInput.value) || 0;
calculateBillAndTip();
});
function calculateBillAndTip() {
if (
bill > 0 &&
bill <= 10000 &&
people > 0 &&
people <= 100 &&
tipPercent >= 0 &&
tipPercent <= 100
) {
const tipPerPerson = (bill * tipPercent) / (100 * people);
const billPerPerson = bill / people + tipPerPerson;
tipPerPersonSpan.innerHTML = tipPerPerson.toFixed(2);
billPerPersonSpan.innerHTML = billPerPerson.toFixed(2);
} else {
tipPerPersonSpan.innerHTML = "0.00";
billPerPersonSpan.innerHTML = "0.00";
}
}