-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
76 lines (63 loc) · 2.66 KB
/
Copy pathscript.js
File metadata and controls
76 lines (63 loc) · 2.66 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const btn = document.querySelector("#btn");
const average = document.querySelector(".average_amount");
const boughtInfo = document.querySelector(".total_bought_amount");
const spentInfo = document.querySelector(".total_spent_amount");
btn.addEventListener("click", ()=> {
let el = `
<div class="add_data">
<input type="number" placeholder="Quantity" min="0" step="0.1" class="numb_input">
<input type="number" placeholder="Price" min="0" step="0.1" class="price_input">
<div class="del" onclick="delBoxes(this)">X</div>
</div>
`;
btn.insertAdjacentHTML("beforebegin", el);
attachInputEventListener();
});
const delBoxes = (e) => {
e.parentNode.remove();
calculate();
}
const formatNumber = (num) => {
return num % 1 !== 0 ? num.toFixed(3) : num.toFixed(2);
}
const calculate = () => {
let totalSpent = 0;
let totalBought = 0;
let numbInputs = document.querySelectorAll(".numb_input");
let priceInputs = document.querySelectorAll(".price_input");
for(let i = 0; i < priceInputs.length; i++){
if (numbInputs[i].value !== "" && priceInputs[i].value !== ""){
totalBought += parseFloat(numbInputs[i].value);
totalSpent += parseFloat(numbInputs[i].value) * parseFloat(priceInputs[i].value);
}
}
let averagePrice = totalBought ? (totalSpent / totalBought) : 0;
let formattedAveragePrice = formatNumber(averagePrice);
let formattedTotalBought = formatNumber(totalBought);
let formattedTotalSpent = formatNumber(totalSpent);
average.innerHTML = !isNaN(formattedAveragePrice) ? `$${formattedAveragePrice}` : `0`;
boughtInfo.innerHTML = !isNaN(formattedTotalBought) ? `${formattedTotalBought}` : `0`;
spentInfo.innerHTML = !isNaN(formattedTotalSpent) ? `$${formattedTotalSpent}` : `0`;
}
const attachInputEventListener = () => {
const allInputs = document.querySelectorAll("input");
allInputs.forEach(inp => {
inp.removeEventListener("input", calculate);
inp.addEventListener("input", calculate);
});
};
attachInputEventListener();
// calculate();
const theme = document.querySelector(".change_mode");
theme.addEventListener("click",() => {
if (theme.classList.contains("dark")) {
theme.classList = "change_mode";
document.documentElement.style.setProperty('--color_one', ' rgb(255,255,255)');
document.documentElement.style.setProperty('--color_two', ' rgb(52,52,52)');
}
else{
theme.classList = "change_mode dark";
document.documentElement.style.setProperty('--color_two', 'rgb(255,255,255)');
document.documentElement.style.setProperty('--color_one', 'rgb(52,52,52)');
};
});