-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
48 lines (40 loc) · 1.71 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
const billValue = document.querySelector("#bill_value")
const tipValue = document.querySelector("#tip_value")
const splitBox = document.querySelector(".pop_up")
const splitValue = document.querySelector("#head_count")
const roundBtn = document.querySelector("#round")
billValue.addEventListener("change", changeTotal)
tipValue.addEventListener("change", changeTotal)
splitValue.addEventListener("change", updateSplit)
roundBtn.addEventListener("click", roundNum)
let total, splitted
function changeTotal(){
const bill = Number(billValue.value)
const tip = Number(tipValue.value)
document.querySelector("#total").innerHTML = roundWithZero(bill*(1+tip/100))
splitBox.style.height = "40%"
splitValue.value && updateSplit()
}
function updateSplit(){
splitted = total/(Number(splitValue.value)+1)
document.querySelector("#split").innerHTML = `<strong>${addDigit(splitted)}</strong>`
}
function roundNum(){
if (splitted && splitValue.value && Array.from(roundBtn.classList).includes("float")){
document.querySelector("#split").innerHTML = `<strong>${roundWithZero(splitted)}</strong>`
roundBtn.classList.toggle("clicked")
roundBtn.classList.toggle("float")
}else if(splitted && splitValue.value && Array.from(roundBtn.classList).includes("clicked")){
document.querySelector("#split").innerHTML = `<strong>$${splitted}</strong>`
roundBtn.classList.toggle("clicked")
roundBtn.classList.toggle("float")
}
}
function roundWithZero(num){
total = Math.round(num*100)/100
return addDigit(total)
}
function addDigit(num){
const temp = num.toString().split(".")
return `${(temp.length == 1) ? `$${num}.00` : (temp[1].length === 1) ? `$${num}0` : `$${num}`}`
}