How to Build a Tip Calculator With HTML, CSS and JavaScript

How to Build a Tip Calculator With HTML, CSS and JavaScript

Build a simple tip calculator using HTML, CSS and vanilla Javascript

A tip calculator is a tool used to calculate the tip for a meal, bar tab, or service gratuity in a restaurant. It also allows one to calculate the tip amount split between a given number of people once the bill and the tip percentage are entered.

In this article, we will learn how to build a tip calculator using HTML, CSS, and JavaScript. This web application computes the total amount you or a group of people will be paying from a bill. Here’s a screenshot of what the finished application looks like:

Prerequisites

  • Basic understanding of HTML, CSS, and JavaScript.

Getting Started

Our tip calculator project contains three parts: HTML, CSS, and JavaScript. We will be creating these three files as follows:

HTML

Open the code editor and create a project folder named "Tip Calculator." Now, create an index.html file and enter the following markup:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <!--LINK CSS FILE-->    
    <link rel="stylesheet" href="style.css" />
    <title>Tip Calculator</title>
  </head>
  <body>
    <div class="calculator">
      <h1 class="title">Tip Calculator</h1>
      <div class="input-group">
        <label for="bill">Bill</label>
        <input type="number" name="bill" id="bill" />
      </div>

      <div class="input-group">
        <label for="tip-percentage">Tip Percentage</label>
        <input type="number" name="tip-percentage" id="tip-percentage" />
      </div>

      <div class="input-group">
        <label for="persons">No. of Persons</label>
        <input type="number" name="persons" id="persons" />
      </div>

      <div class="result input-group">
        <h2 class="total">Total</h2>
        <div id="totalOutput"></div>
      </div>
      <button class="calculate-btn">Calculate</button>
    </div>
    <!--LINK JAVASCRIPT FILE-->
    <script src="./script.js"></script>
  </body>
</html>

As you can see, our CSS and JavaScript files are linked to HTML respectively as shown:

<link rel="stylesheet" href="style.css" />
 <script src="./script.js"></script>

A few notes:

The markup contains a div with the class name of calculator. This wraps the inputs for bill, tip percentage, number of persons and also the calculate button elements.

The .input-group represents each input field for our web app. It contains the label and the input element.

Ensure that the for attribute value in <label> matches the id value in <input /> tag. For example:

<label for="persons">
<input id="persons" />

CSS

Then, create a style.css file. Here, you're going to add CSS styling to the tip calculator. First, let's remove the default browser styling by adding:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

Next, let's change the style of the body element and align the child components:

body {
  background-color: #222;
  font-family: "Inter", sans-serif;
  font-size: 1rem;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin: 0 auto;
  width: 100vw;
  height: 100vh;
}

Below are the complete CSS styles for our project:

/*style.css */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background-color: #222;
  font-family: "Inter", sans-serif;
  font-size: 1rem;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin: 0 auto;
  width: 100vw;
  height: 100vh;
}

.title {
  font-size: 1.5rem;
  margin: 10px 0 20px;
  text-align: center;
}

.calculator {
  background-color: #fff;
  border-radius: 5px;
  color: #222;
  padding: 20px;
}

.input-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 12px 5px;
}

label {
  color: #2e2e2e;
  font-family: "Inter", sans-serif;
  font-size: 1rem;
  font-weight: 600;
  margin-right: 20px;
}

input {
  border: 1px solid #b8b8b8;
  border-radius: 5px;
  outline: none;
  padding: 8px;
}

input:focus {
  border: 1px solid #fe4880;
}

#totalOutput {
  border-bottom: 1px solid #222;
  font-size: 1.2rem;
  font-weight: 600;
  text-align: center;
  padding: 5px;
  margin: 5px;
  width: 100%;
}

button {
  background-color: #fe4880;
  border: none;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
  outline: none;
  font-size: 20px;
  margin-top: 10px;
  padding: 10px 15px;
  width: 100%;
  transition: all 0.3 ease-in-out;
}

button:active,
button:hover {
  background-color: #df1857;
}

That concludes the CSS section; let's move on to script.js and begin adding logic to our tip calculator to make it functional.

JavaScript

The calculateTotal() function contains all the code for the working of the app

In this function, we will compute values for the bill, tip percent, tip amount, total result, and total per person.

Let's discuss everything step by step:

First, derive the HTML elements required to build our web app. In this case, we are using the querySelector. This works like getElementById and getElementByClassName methods.

let inputElems = document.querySelectorAll("input[type='number']");
const bill = document.querySelector("#bill");
const tip = document.querySelector("#tip-percentage");
const total = document.querySelector("#totalOutput");
const numberOfPersons = document.querySelector("#persons");
const calculateBtn = document.querySelector(".calculate-btn");

Step 1: Create a function named "calculateTotal".

function calculateTotal() {
{
  //code to be executed
}

Step 2: Add event handlers to the calculateTotal() function. The event listeners call the calculateTotal() function when we click on the Calculate button or hit the ENTER key respectively.

calculateBtn.addEventListener("click", calculateTotal);

window.addEventListener("keydown", (e) => {
  if (e.keyCode === 13) {
    calculateTotal();
  }
});

Below is the event handler that sets all the inputs to an empty string on load.

window.addEventListener("load", () => {
  inputElems.forEach((input) => (input.value = ""));
});

Step 3: Compute the bill, tip percentage, and total

We will obtain the values for the bill and tip percentage using the document.querySelector method and the .value attribute attached to it. The product of bill and tip percentage value returns the tipAmountValue.

let billValue = bill.value;
let tipPercentValue = tip.value / 100;
let tipAmountValue = billValue * tipPercentValue;

The parseFloat() is a javascript method that accepts a string input and converts it into a floating-point number. This is used to derive the totalPerPerson value.

let totalResult = parseFloat(billValue) + parseFloat(tipAmountValue);
let totalPerPerson = totalResult / numberOfPersons.value;
total.innerHTML = `${totalPerPerson.toLocaleString()} (per person)`;

The total result is the sum of the bill amount and the tip amount. For a group of two or more, we will obtain the total per person (how much each individual will pay) by dividing the total by the number of people involved.

The toLocaleString() method converts the total per person into a human-readable string. Now, we will be able to insert the values inside the <div> with the class name totalOutput using the innerHTML property.

 <div class="result input-group">
     <h2 class="total">Total</h2>
     <div id="totalOutput"></div>
 </div>

Here's what the complete JavaScript code should look like:

// script.js
let inputElems = document.querySelectorAll("input[type='number']");
const bill = document.querySelector("#bill");
const tip = document.querySelector("#tip-percentage");
const total = document.querySelector("#totalOutput");
const numberOfPersons = document.querySelector("#persons");
const calculateBtn = document.querySelector(".calculate-btn");

window.addEventListener("load", () => {
  inputElems.forEach((input) => (input.value = ""));
});

calculateBtn.addEventListener("click", calculateTotal);

window.addEventListener("keydown", (e) => {
  if (e.keyCode === 13) {
    calculateTotal();
  }
});

function calculateTotal() {
  let billValue = bill.value;
  let tipPercentValue = tip.value / 100;
  let tipAmountValue = billValue * tipPercentValue;
  let totalResult = parseFloat(billValue) + parseFloat(tipAmountValue);
  let totalPerPerson = totalResult / numberOfPersons.value;
  total.innerHTML = `${totalPerPerson.toLocaleString()} (per person)`;
}

You have just created a tip calculator. You can find the source code in this GitHub Repository or see Live Demo.

Conclusion

Now that you've made it to the end of this project, you have a functional tip calculator working in your web browser. If you found this article helpful, please give it a like and share it. Happy Coding!