|
| 1 | +const billInput = document.querySelector(".bill"); |
| 2 | +const splitInput = document.querySelector(".split"); |
| 3 | +const tipButtons = document.querySelectorAll(".tip-btn"); |
| 4 | +const customTipInput = document.getElementById("custom-tip"); |
| 5 | +const tipAmountDisplay = document.getElementById("tip-amount"); |
| 6 | +const totalBillDisplay = document.getElementById("total-bill"); |
| 7 | +const perPersonDisplay = document.getElementById("per-person"); |
| 8 | + |
| 9 | +let tipPercentage = 0; |
| 10 | + |
| 11 | +tipButtons.forEach(btn => { |
| 12 | + btn.addEventListener("click", () => { |
| 13 | + tipPercentage = Number(btn.dataset.tip); |
| 14 | + customTipInput.value = ""; // clear custom tip |
| 15 | + tipButtons.forEach(b => b.classList.remove("active")); |
| 16 | + btn.classList.add("active"); |
| 17 | + calculateTotals(); |
| 18 | + }); |
| 19 | +}); |
| 20 | + |
| 21 | + |
| 22 | +[billInput, splitInput, customTipInput].forEach(input => { |
| 23 | + input.addEventListener("input", () => calculateTotals()); |
| 24 | +}); |
| 25 | + |
| 26 | + |
| 27 | +function calculateTotals() { |
| 28 | + const bill = parseFloat(billInput.value); |
| 29 | + const people = parseInt(splitInput.value) || 1; |
| 30 | + const customTip = parseFloat(customTipInput.value); |
| 31 | + |
| 32 | + // Use custom tip if entered |
| 33 | + const tipPercent = customTip > 0 ? customTip : tipPercentage; |
| 34 | + |
| 35 | + // Prevent calculation for empty bill |
| 36 | + if (isNaN(bill) || bill <= 0) { |
| 37 | + updateDisplay(0, 0, 0); |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + const tipAmount = (bill * tipPercent) / 100; |
| 42 | + const totalBill = bill + tipAmount; |
| 43 | + const perPerson = totalBill / people; |
| 44 | + |
| 45 | + updateDisplay(tipAmount, totalBill, perPerson); |
| 46 | +} |
| 47 | + |
| 48 | +function updateDisplay(tip, total, perPerson) { |
| 49 | + tipAmountDisplay.textContent = `Rs${tip.toFixed(2)}`; |
| 50 | + totalBillDisplay.textContent = `Rs${total.toFixed(2)}`; |
| 51 | + perPersonDisplay.textContent = `Rs${perPerson.toFixed(2)}`; |
| 52 | +} |
| 53 | + |
| 54 | +const themeToggle = document.getElementById("themeToggle"); |
| 55 | +const body = document.body; |
| 56 | + |
| 57 | +const currentTheme = localStorage.getItem("theme") || "light"; |
| 58 | +if (currentTheme === "dark") { |
| 59 | + body.classList.add("dark-mode"); |
| 60 | +} |
| 61 | + |
| 62 | +themeToggle.addEventListener("click", () => { |
| 63 | + body.classList.toggle("dark-mode"); |
| 64 | + |
| 65 | + const theme = body.classList.contains("dark-mode") ? "dark" : "light"; |
| 66 | + localStorage.setItem("theme", theme); |
| 67 | +}); |
0 commit comments