Instantly share code, notes, and snippets.

Embed
What would you like to do?
<!DOCTYPE html>
<html>
<head>
<title>Tip Calculator</title>
<style type="text/css">
body {
margin-left: auto;
margin-right: auto;
max-width: 40em;
width: 88%;
}
#owed {
font-weight: bold;
}
</style>
</head>
<body>
<h1>Tip Calculator</h1>
<div class="tip-calculator">
<div>
<label for="amount">Total Amount</label>
<input type="number" min="0" value="0" name="amount" id="amount">
</div>
<div>
<label for="people">Number of People</label>
<input type="number" step="1" min="1" value="1" name="people" id="people">
</div>
<div>
<label for="tip">Tip (%)</label>
<input type="number" step="1" min="0" value="0" name="tip" id="tip">
</div>
<div id="owed" aria-live="polite"></div>
</div>
<script src="https://cdn.polyfill.io/v2/polyfill.min.js"></script>
<script>
// Variables
var amount = document.querySelector('#amount');
var people = document.querySelector('#people');
var tip = document.querySelector('#tip');
var owed = document.querySelector('#owed');
/**
* Calculate total amount per person
* @return {Number} The amount owed per person
*/
var calculateAmountOwed = function () {
// Default values
var tipAmount = 0;
var perPerson = 0;
// Calculate tip amount
if (tip.value.length > 0) {
tipAmount = parseFloat(tip.value) / 100;
}
// Calculate per person cost
if (amount.value.length > 0 && people.value.length > 0) {
perPerson = parseFloat(amount.value) / Math.ceil(people.value);
}
// Calculate amount owed
var owed = Math.ceil(perPerson + (perPerson * tipAmount));
return owed;
};
/**
* Handle field change events
*/
var changeHandler = function (event) {
// Make sure changed field is in the tip calculator
if (!event.target.closest('.tip-calculator')) return;
// Update the DOM
owed.innerHTML = 'You owe $' + calculateAmountOwed() + ' per person.';
};
// Listen for field changes and update amount owed
document.addEventListener('input', changeHandler, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment