top of page
Writer's pictureWeb Coding

How to create a tip calculator with JavaScript

Today I will be teaching you how to create a tip calculator using only HTML, CSS and JavaScript.


HTML

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <link rel="stylesheet" href="style.css">
</head>
<body>
 <div id="calc">
 <h2>Tip Calculator</h2>
 <div class="row"> <p class="column">Bill: ($)</p> <input type="number" class="column1" id="billAmount"> </div>
 <div class="row"> <p class="column">Tip Percent: (%)</p> <input type="number" class="column1" id="percentage"></div>
 <div class="row"> <button id="Calculate">Calculate Tip</button> </div>
 <div class="row"><p id="amount" class="column">Amount:</p> <span id="result" class="column1"></span> </div>
 </div>
 <script src="script.js"></script>
</body>

</html>


CSS

*{
 padding0;
 margin0;
}

body{
 min-height100vh;
 displayflex;
 align-itemscenter;
 justify-contentcenter;
 background-color#19181A;
}

#calc{
 background-color#A16E83;
 border1px solid black;
 min-height20vh;
 width50%;
 border-radius25px;
 font-size16px;
}

h2{
 padding-top3vh;
 text-aligncenter;
 padding-bottom1vh;
}

#calc p{
 text-alignend;
}

.row {
 displayflex;
 flex-directionrow;
 justify-contentcenter;
  }
 

.column {
 flex-basis25%;
 margin-right1%;
}

.column1 {
 flex-basis45%;
 margin-left1%;
}

#Calculate{
 margin-top5px;
}

JavaScript

let bill = document.getElementById('billAmount');
let percentage = document.getElementById('percentage');
let result = document.getElementById('result');
let calcBtn = document.getElementById('Calculate');

calcBtn.addEventListener('click'calculateTip);

function calculateTip(){
 let tip = billAmount.value * (percentage.value / 100);
 console.log(tip);
 result.innerHTML = "$ " + tip.toFixed(2);
}

If you found this blog post helpful don’t forget to check out my other projects and if you want more content follow me on


YouTube: https://www.youtube.com/channel/UC2nxqB2usQIS2c8zwVZKWEQ

Instagram: https://www.instagram.com/coding_for_the_web/

Twitter: https://twitter.com/LearnWebCoding


19 views

Comments


bottom of page