I've built a fairly simple tip calculator. What I have so far is a bunch of functions to calculate each tip amount and calling each w/ eventListenerwith eventListener
.
It works however trying to see if there's a better approach that would modularize the code. I'm thinking possibilities include passing functions as arguments or functions calling other functions but can't figure it out yet.
Here's the code:
HTML
HTML
<label>Bill Amount: </label><input type="text" id="billInput">
<br><br>
<button class="tenPercent">Tip 10%</button>
<br>
<button class="fifteenPercent">Tip 15%</button>
<br>
<button class="twentyPercent">Tip 20%</button>
<br><br>
<label>Custom Tip Percentage: </label><input type="text" id="customTip"> <button class="customTipBtn">Tip Custom Amount</button>
<br><br>
<p id="tipAmount"></p>
JS
JS
var tenPerBtn = document.querySelector('.tenPercent');
var fifteenPerBtn = document.querySelector('.fifteenPercent');
var twentyPerBtn = document.querySelector('.twentyPercent');
var customPerBtn = document.querySelector('.customTipBtn');
var bill = document.getElementById('billInput');
var tipSuggestion = document.getElementById('tipAmount');
function calcTen(){
var billInput = bill.value;
var tipAmount = billInput * .1;
tipSuggestion.innerHTML = 'A ten percent tip would equal $' + tipAmount;
}
function calcFifteen(){
var billInput = bill.value;
var tipAmount = billInput * .15;
tipSuggestion.innerHTML = 'A fifteen percent tip would equal $' + tipAmount;
}
function calcTwenty(){
var billInput = bill.value;
var tipAmount = billInput * .2;
tipSuggestion.innerHTML = 'A twenty percent tip would equal $' + tipAmount;
}
function calcCustom(){
var billInput = bill.value;
var customTipAmount = document.querySelector('#customTip').value;
var tipAmount = billInput * customTipAmount;
tipSuggestion.innerHTML = 'A ' + customTipAmount + ' percent tip would equal $' + tipAmount;
}
tenPerBtn.addEventListener('click', calcTen)
fifteenPerBtn.addEventListener('click', calcFifteen)
twentyPerBtn.addEventListener('click', calcTwenty)
customPerBtn.addEventListener('click', calcCustom)