A simple tip calculator that asks for the total bill amount, service quality (used to determine what percentage of the total cost will be tipped), and how many people are sharing the bill (used to split the tip so that everyone pays the same amount).
I am primarily looking for possible improvements to performance or readability, but any suggestion is welcome.
See the code in action - jsFiddle
Link to repository - GitHub
// Pointers
const billAmountAlertPointer = document.getElementById('billAmountAlert');
const tipPercentageAlertPointer = document.getElementById('tipPercentageAlert');
const numberOfPeoplePointer = document.getElementById('numberOfPeople');
const serviceQualityPointer = document.getElementById('serviceQuality');
const numberOfPeopleLabelPointer = document.getElementById('numberOfPeopleLabel');
const eachPointer = document.getElementById('each');
const soundPointer = document.getElementById('cashRegisterSound');
soundPointer.volume = 0.05;
var numberOfPeople = 1;
// Display the text 'people' next to the input if the number of people is higher than 1
numberOfPeoplePointer.oninput = function(){
numberOfPeople = numberOfPeoplePointer.value;
numberOfPeople > 1 ? numberOfPeopleLabelPointer.innerHTML = 'people' : numberOfPeopleLabelPointer.innerHTML = 'lone wolf';
};
document.getElementById('calculateButton').addEventListener('click', function() {
let billAmount = document.getElementById('billAmount').value;
let tipPercentage = serviceQualityPointer.value;
// Only proceed if both the billAmount and the tipPercentage have a value
if (billAmount !== '' && tipPercentage !== ''){
setDisplay(billAmountAlertPointer, 'none');
setDisplay(tipPercentageAlertPointer, 'none');
let tipAmount = (billAmount / (100 / tipPercentage)) / numberOfPeople;
document.getElementById('tipAmount').innerHTML = '$' + tipAmount;
/* If the number of people sharing the bill is higher than 1, display the text 'each'
next to the input. Otherwise, don't.*/
numberOfPeople > 1 ? setDisplay(eachPointer, 'block') : setDisplay(eachPointer, 'none');
document.getElementById('tipAmountContainer').style.display = 'block';
// Play the cash register sound
playSound();
} else{
// If the user hasn't entered the bill amount, display an alert
if (billAmount === ''){
setDisplay(billAmountAlertPointer, 'inline');
}
// If the user hasn't entered the tip percentage, display an alert
if (tipPercentage === ''){
setDisplay(tipPercentageAlertPointer, 'inline');
}
}
});
function setDisplay(element, value){
element.style.display = value;
}
function playSound(){
soundPointer.play();
}
document.getElementById('billAmount')
,document.getElementById('tipAmount')
anddocument.getElementById('tipAmountContainer')
not declared at// Pointers
? \$\endgroup\$