forked from sumn2u/learn-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
60 lines (49 loc) · 1.83 KB
/
script.js
File metadata and controls
60 lines (49 loc) · 1.83 KB
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
// Tip Calculator Logic
const billInput = document.getElementById('bill');
const tipButtons = document.querySelectorAll('.tip-btn');
const customTipInput = document.getElementById('customTip');
const splitInput = document.getElementById('split');
const tipDisplay = document.getElementById('tip');
const totalDisplay = document.getElementById('total');
const eachDisplay = document.getElementById('each');
const resultsDiv = document.getElementById('results');
let selectedTip = 10;
// Event listeners for tip buttons
tipButtons.forEach(btn => {
btn.addEventListener('click', () => {
tipButtons.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
selectedTip = parseFloat(btn.dataset.tip);
customTipInput.value = '';
calculate();
});
});
// Custom tip input
customTipInput.addEventListener('input', () => {
tipButtons.forEach(b => b.classList.remove('active'));
selectedTip = parseFloat(customTipInput.value) || 0;
calculate();
});
// Bill, split inputs
billInput.addEventListener('input', calculate);
splitInput.addEventListener('input', calculate);
function calculate() {
const bill = parseFloat(billInput.value);
const people = Math.max(1, parseInt(splitInput.value, 10) || 1);
if (isNaN(bill) || bill <= 0 || isNaN(selectedTip) || selectedTip < 0) {
tipDisplay.textContent = "0.00";
totalDisplay.textContent = "0.00";
eachDisplay.textContent = "0.00";
resultsDiv.style.background = '#fee2e2';
return;
}
const tip = bill * selectedTip / 100;
const total = bill + tip;
const each = total / people;
tipDisplay.textContent = tip.toFixed(2);
totalDisplay.textContent = total.toFixed(2);
eachDisplay.textContent = each.toFixed(2);
resultsDiv.style.background = '#f1f5f9';
}
// Initial calculation on load
calculate();