-
Notifications
You must be signed in to change notification settings - Fork 0
/
JS
81 lines (66 loc) · 2.44 KB
/
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
// Define variables and select elements
const billInput = document.getElementById("bill");
const customTipInput = document.getElementById("custom-tip");
const numPeopleInput = document.getElementById("people");
const tipAmounts = document.querySelectorAll(".tip-amount");
const tipAmountDisplay = document.querySelector("#tip-amount-per-person span");
const totalAmountDisplay = document.querySelector("#total-per-person span");
// Initialize values
let bill = 0;
let customTip = 0;
let numPeople = 1;
let activeButton = null; // Initialize the active button variable
// Update bill value and calculate results
function updateBill(event) {
bill = parseFloat(event.target.value);
calculateResults();
}
// Update custom tip value and calculate results
function updateCustomTip(event) {
customTip = parseFloat(event.target.value);
calculateResults();
}
// Update number of people and calculate results
function updateNumPeople(event) {
numPeople = parseInt(event.target.value);
calculateResults();
}
// Toggle active class on tip amount buttons
function toggleActive(event) {
event.preventDefault();
const currentButton = event.currentTarget;
if (activeButton) {
activeButton.classList.remove("active"); // Remove the active class from the previous button
}
currentButton.classList.add("active");
customTip = parseFloat(currentButton.dataset.tip);
customTipInput.value = ""; // Clear custom tip input
calculateResults();
activeButton = currentButton; // Update the active button variable
}
// Add event listeners for tip amount buttons
tipAmounts.forEach((tipAmount) => {
tipAmount.addEventListener("click", toggleActive);
});
// Add event listeners to input fields
billInput.addEventListener("input", updateBill);
customTipInput.addEventListener("input", updateCustomTip);
numPeopleInput.addEventListener("input", updateNumPeople);
// Add event listener for clicks on the custom tip input field
customTipInput.addEventListener("click", () => {
tipAmounts.forEach((tipAmount) => {
tipAmount.classList.remove("active");
});
});
// Add event listener for clicks on the tip amount buttons
tipAmounts.forEach((tipAmount) => {
tipAmount.addEventListener("click", (event) => {
const currentButton = event.currentTarget;
tipAmounts.forEach((tipAmount) => {
if (tipAmount !== currentButton) {
tipAmount.classList.remove("active");
}
});
activeButton = currentButton; // Update the active button variable
});
});