-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
85 lines (84 loc) · 2.54 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
const btns = document.querySelectorAll('.btn')
const billInput = document.querySelector('.billInput')
const peopleInput = document.querySelector('#people')
const customInput = document.querySelector('.custom')
const tip = document.querySelector('#tip')
const totalTip = document.querySelector('#total')
const resetBtn = document.querySelector('.reset')
let numberOfPeople = 1
let amount = null
let percent = null
// Adding active state to buttons
btns.forEach((btn) => {
btn.addEventListener('click', (e) => {
btns.forEach((item) => {
item.classList.remove('active')
})
e.target.classList.add('active')
percent = btn.getAttribute('data-percent')
customInput.value = ''
customInput.classList.remove('active')
calculateTip(numberOfPeople, percent, amount)
})
})
billInput.addEventListener('input', (e) => {
amount = e.target.value
calculateTip(numberOfPeople, percent, amount)
})
peopleInput.addEventListener('input', (e) => {
numberOfPeople = e.target.value
calculateTip(numberOfPeople, percent, amount)
})
customInput.addEventListener('input', (e) => {
btns.forEach((item) => {
item.classList.remove('active')
})
percent = e.target.value
calculateTip(numberOfPeople, percent, amount)
})
customInput.addEventListener('blur', (e) => {
if (e.target.value.length > 0) {
customInput.classList.add('active')
} else {
customInput.classList.remove('active')
}
})
// Calculate Tip
const calculateTip = (numberOfPeople, percent, amount) => {
if (!numberOfPeople || !amount || !percent) return
const tipPerPerson = ((percent / 100) * amount).toFixed(2)
const sumOfTip = (tipPerPerson * numberOfPeople).toFixed(2)
tip.textContent = `$${tipPerPerson}`
totalTip.textContent = `$${sumOfTip}`
}
// CHECKING FOR INVALID INPUT VALUES OR NULL
billInput.addEventListener('blur', (e) => {
if (e.target.value.length === 0) {
billInput.classList.add('invalid')
} else {
billInput.classList.remove('invalid')
calculateTip(numberOfPeople, percent, amount)
}
})
peopleInput.addEventListener('blur', (e) => {
if (e.target.valueAsNumber === 0) {
peopleInput.classList.add('invalid')
} else {
peopleInput.classList.remove('invalid')
calculateTip(numberOfPeople, percent, amount)
}
})
// resetting calculator
resetBtn.addEventListener('click', () => {
btns.forEach((item) => {
item.classList.remove('active')
})
billInput.value = ''
peopleInput.value = ''
customInput.value = ''
numberOfPeople = 1
amount = null
percent = null
tip.textContent = `$0.00`
totalTip.textContent = `$0.00`
})