-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
53 lines (40 loc) · 1.92 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
function fuelCalculator() {
// * Selecting elements from DOM
const distance = +document.getElementById('distance').value
const averageConsumption = +document.getElementById('average').value
const costOfLiter = +document.getElementById('cost').value
const resultCost = document.getElementById('tripcost')
const resultFuel = document.getElementById('fuelcost')
const currency = document.getElementById('currency')
// * Math logic
const fuelPerKm = +(averageConsumption / 100).toFixed(3)
const totalFuel = +(fuelPerKm * distance).toFixed(2)
const tripCost = +(totalFuel * costOfLiter).toFixed(2)
// ? This is way to select active option on dropdown list (currency.options[currency.selectedIndex].value)
function currencyVario() {
if (currency.options[currency.selectedIndex].value === 'uah') return '₴'
if (currency.options[currency.selectedIndex].value === 'usd') return '$'
if (currency.options[currency.selectedIndex].value === 'eur') return '€'
}
// * Updating HTML with all the math calculations
resultCost.value = `${currencyVario()}${tripCost}`
resultFuel.value = `${totalFuel}L`
resultCost.innerHTML = resultCost.value
resultFuel.innerHTML = resultFuel.value
}
// * Selecting event target element from DOM:
const button = document.querySelector('#button')
// * Adding an event listener to the button:
button.addEventListener('click', fuelCalculator)
// ? Event handler function to update placeholder value, due to selected currency
function placeholderCurrSwitcher() {
const costInput = document.getElementById('cost')
if (currency.options[currency.selectedIndex].value === 'uah')
costInput.placeholder = '₴/L'
if (currency.options[currency.selectedIndex].value === 'usd')
costInput.placeholder = '$/L'
if (currency.options[currency.selectedIndex].value === 'eur')
costInput.placeholder = '€/L'
}
// * Adding event listener
currency.onchange = placeholderCurrSwitcher