Easy Tip Calculator Using HTML, CSS, and JavaScript

Faraz

By Faraz - Last Updated:

Learn to build a tip calculator with HTML, CSS, and JavaScript. This guide covers everything from setup to coding.


easy-tip-calculator-using-html-css-and-javascript.webp

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Creating a tip calculator is a fun and practical project for anyone learning web development. This calculator helps users determine how much to tip based on their bill amount, the percentage they want to tip, and how many people share the bill.

In this guide, we will learn how to make a simple tip calculator using three essential web technologies: HTML for structure, CSS for styling, and JavaScript for functionality. You don't need to be an expert coder to follow this tutorial; basic knowledge of these technologies is enough to get you started.

Before diving in, make sure you have a text editor installed, like Visual Studio Code, and a web browser for testing your calculator. By the end of this tutorial, you will have a working tip calculator that you can use and customize. Let’s get started!

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our tip calculator.

Let's break down the HTML code step by step:

1. Document Type Declaration

<!DOCTYPE html>
  • This declaration defines the document as an HTML5 document. It helps the browser render the page correctly.

2. HTML Tag

<html lang="en">
  • The <html> tag is the root element of the HTML document. The lang="en" attribute specifies that the content is in English, which helps with accessibility and search engines.

3. Head Section

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Modern Tip Calculator</title>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="styles.css">
</head>
  • The <head> section contains meta-information about the document.
    • <meta charset="UTF-8">: Sets the character encoding to UTF-8, which supports most characters and symbols.
    • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Ensures the page is responsive and scales correctly on different devices.
    • <title>Modern Tip Calculator</title>: Sets the title of the web page, which appears in the browser tab.
    • <link href="https://fonts.googleapis.com/... : This link imports the Poppins font from Google Fonts for use in the document.
    • <link rel="stylesheet" href="styles.css">: Links to an external CSS file (styles.css) that contains the styles for the webpage.

4. Body Section

<body>
  <div class="container">
    <div class="tip-card">
      ...
    </div>
  </div>
  <script src="script.js"></script>
</body>
  • The <body> section contains the content that is displayed on the webpage.
    • <div class="container">: A wrapper for the content, often used for layout purposes.
    • <div class="tip-card">: A card-like container specifically for the tip calculator, which helps in styling and organization.
    • <script src="script.js"></script>: Links to an external JavaScript file (script.js) that contains the functionality for the calculator.

5. Tip Card Content

Inside the tip-card div, we have several elements:

a. Card Header

<div class="card-header">
  <h1>Tip Calculator</h1>
</div>
  • This contains an <h1> heading that displays the title "Tip Calculator."

b. Input Groups

These sections take user input for the calculation:

<div class="input-group">
  <label for="billAmount">Bill Amount ($)</label>
  <input type="number" id="billAmount" placeholder="Enter bill amount">
</div>
  • Each input group consists of a <label> and an <input> element.
    • Bill Amount: The user enters the total bill amount.
    • Tip Percentage: The user enters the desired tip percentage.
    • Number of People: The user enters how many people will share the bill.
  • Each <input> has an id for JavaScript access and a placeholder for user guidance.

c. Button Group

<div class="button-group">
  <button class="btn calculate-btn" onclick="calculateTip()">Calculate</button>
  <button class="btn reset-btn" onclick="resetCalculator()">Reset</button>
</div>
  • This section contains two buttons:
    • Calculate Button: Calls the calculateTip() function when clicked to perform the calculation.
    • Reset Button: Calls the resetCalculator() function to clear the inputs and results.

d. Results Display

<div class="results">
  <div class="result-item">
    <span>Tip per Person:</span>
    <span id="tipAmount">$0.00</span>
  </div>
  <div class="result-item">
    <span>Total per Person:</span>
    <span id="totalAmount">$0.00</span>
  </div>
  <div class="result-item">
    <span>Total Bill:</span>
    <span id="totalBill">$0.00</span>
  </div>
</div>
  • This section displays the results after the calculation:
    • Tip per Person: Shows the calculated tip amount per person.
    • Total per Person: Shows the total amount each person needs to pay, including the tip.
    • Total Bill: Displays the overall bill amount, including the tip.

Step 2 (CSS Code):

Once the basic HTML structure of the calculator is in place, the next step is to add styling to the calculator using CSS.

Let's break down the CSS code step by step to explain its purpose and styling rules.

1. Universal Selector

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
  • *: This universal selector applies styles to all elements on the page.
    • margin: 0;: Resets the margin for all elements to remove any default spacing.
    • padding: 0;: Resets the padding for all elements to ensure consistency.
    • box-sizing: border-box;: Changes the box model so that the width and height of elements include padding and borders. This makes sizing elements more intuitive.
    • font-family: 'Poppins', sans-serif;: Sets the default font to Poppins, with a fallback to sans-serif if Poppins is unavailable.

2. Body Styles

body {
  background: #825CFF;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
  • background: #825CFF;: Sets a purple background color for the entire body.
  • display: flex;: Uses Flexbox layout to center the content.
  • align-items: center;: Vertically centers items within the body.
  • justify-content: center;: Horizontally centers items within the body.
  • height: 100vh;: Sets the body's height to 100% of the viewport height.

3. Container Styles

.container {
  width: 100%;
  max-width: 400px;
  padding: 20px;
}
  • width: 100%;: Allows the container to take the full width of its parent.
  • max-width: 400px;: Restricts the maximum width to 400 pixels, ensuring the design remains manageable on larger screens.
  • padding: 20px;: Adds space inside the container.

4. Tip Card Styles

.tip-card {
  background-color: #fff;
  border-radius: 15px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  padding: 30px;
  animation: slideIn 0.5s ease-out;
}
  • background-color: #fff;: Sets a white background for the tip card.
  • border-radius: 15px;: Rounds the corners of the card for a softer appearance.
  • box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);: Adds a subtle shadow effect to give the card a lifted appearance.
  • padding: 30px;: Provides space inside the card for its content.
  • animation: slideIn 0.5s ease-out;: Applies a slide-in animation when the card appears.

5. Card Header Styles

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.card-header h1 {
  font-size: 24px;
  color: #333;
}
  • .card-header: Uses Flexbox to align items within the header.
    • justify-content: space-between;: Distributes space between items, pushing them to the edges.
    • margin-bottom: 20px;: Adds space below the header.
  • .card-header h1: Styles the main heading.
    • font-size: 24px;: Sets the font size of the heading.
    • color: #333;: Applies a dark gray color for better readability.

6. Input Group Styles

.input-group {
  margin-bottom: 15px;
  text-align: left;
}

.input-group label {
  font-weight: 600;
  margin-bottom: 5px;
  display: block;
  color: #555;
}

.input-group input {
  width: 100%;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #ddd;
  font-size: 16px;
  background-color: #f5f5f5;
}
  • .input-group: Styles each group of inputs.
    • margin-bottom: 15px;: Adds space below each input group.
    • text-align: left;: Aligns text to the left for better readability.
  • .input-group label: Styles the labels for inputs.
    • font-weight: 600;: Makes the label text bold.
    • margin-bottom: 5px;: Adds space below the label.
    • display: block;: Ensures the label takes the full width.
    • color: #555;: Applies a medium gray color for contrast.
  • .input-group input: Styles the input fields.
    • width: 100%;: Makes inputs take the full width of their parent.
    • padding: 12px;: Adds padding for comfort.
    • border-radius: 8px;: Rounds the input corners.
    • border: 1px solid #ddd;: Adds a light gray border.
    • font-size: 16px;: Sets a comfortable font size for input text.
    • background-color: #f5f5f5;: Applies a light gray background for inputs.

7. Button Group Styles

.button-group {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}
  • .button-group: Styles the button container.
    • display: flex;: Uses Flexbox for layout.
    • gap: 10px;: Adds space between buttons.
    • margin-top: 15px;: Adds space above the button group.

8. Button Styles

.btn {
  flex: 1;
  padding: 15px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.calculate-btn {
  background-color: #4caf50;
  color: white;
}

.calculate-btn:hover {
  background-color: #43a047;
}

.reset-btn {
  background-color: #f44336;
  color: white;
}

.reset-btn:hover {
  background-color: #e53935;
}
  • .btn: Base styles for buttons.
    • flex: 1;: Makes buttons expand to fill available space equally.
    • padding: 15px;: Adds padding for comfort.
    • border: none;: Removes default button borders.
    • border-radius: 8px;: Rounds button corners.
    • font-size: 16px;: Sets a comfortable font size.
    • cursor: pointer;: Changes the cursor to indicate a clickable element.
    • transition: background-color 0.3s;: Smoothens the background color change on hover.
  • .calculate-btn: Specific styles for the calculate button.
    • background-color: #4caf50;: Sets a green background.
    • color: white;: Sets the text color to white.
  • :hover styles: Change background color on hover for both buttons to provide visual feedback.
  • .reset-btn: Styles for the reset button with a red background.

9. Results Styles

.results {
  margin-top: 20px;
}

.result-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 18px;
}

.result-item span {
  color: #333;
}
  • .results: Container for the results display.
    • margin-top: 20px;: Adds space above the results.
  • .result-item: Each result's styling.
    • display: flex;: Uses Flexbox to layout items.
    • justify-content: space-between;: Distributes space between items.
    • margin-bottom: 8px;: Adds space below each result item.
    • font-size: 18px;: Sets a larger font size for results.
  • .result-item span: Styles the text within result items.
    • color: #333;: Applies a dark gray color.

10. Animation Keyframes

@keyframes slideIn {
  from {
    transform: translateY(-30px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
  • @keyframes slideIn: Defines a slide-in animation.
    • from: The starting state of the animation.
      • transform: translateY(-30px);: Starts 30 pixels above its final position.
      • opacity: 0;: Starts fully transparent.
    • to: The ending state of the animation.
      • transform: translateY(0);: Ends at its original position.
      • opacity: 1;: Ends fully visible.
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}

body {
  background: #825CFF;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.container {
  width: 100%;
  max-width: 400px;
  padding: 20px;
}

.tip-card {
  background-color: #fff;
  border-radius: 15px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  padding: 30px;
  animation: slideIn 0.5s ease-out;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.card-header h1 {
  font-size: 24px;
  color: #333;
}

.input-group {
  margin-bottom: 15px;
  text-align: left;
}

.input-group label {
  font-weight: 600;
  margin-bottom: 5px;
  display: block;
  color: #555;
}

.input-group input {
  width: 100%;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #ddd;
  font-size: 16px;
  background-color: #f5f5f5;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.btn {
  flex: 1;
  padding: 15px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.calculate-btn {
  background-color: #4caf50;
  color: white;
}

.calculate-btn:hover {
  background-color: #43a047;
}

.reset-btn {
  background-color: #f44336;
  color: white;
}

.reset-btn:hover {
  background-color: #e53935;
}

.results {
  margin-top: 20px;
}

.result-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 18px;
}

.result-item span {
  color: #333;
}

@keyframes slideIn {
  from {
    transform: translateY(-30px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript.

Let's break down JavaScript code. This code consists of two main functions: calculateTip() and resetCalculator(). These functions work together to calculate and display the tip amount based on user input.

1. Function: calculateTip()

This function calculates the tip amount based on the user's inputs.

Step-by-Step Explanation:

function calculateTip() {
  • Defines the calculateTip function.
  const billAmount = parseFloat(document.getElementById('billAmount').value);
  const tipPercent = parseFloat(document.getElementById('tipPercent').value);
  const people = parseInt(document.getElementById('people').value);
  • Retrieves values from input fields with IDs billAmount, tipPercent, and people.
  • parseFloat() converts the string input to a floating-point number for billAmount and tipPercent.
  • parseInt() converts the string input to an integer for people.
  if (isNaN(billAmount) || isNaN(tipPercent) || isNaN(people) || people <= 0) {
    alert('Please enter valid inputs.');
    return;
  }
  • Checks if any of the retrieved values are NaN (not a number) or if the number of people is less than or equal to 0.
  • If any condition is true, an alert is displayed to the user, and the function exits early using return.
const totalTip = (billAmount * tipPercent) / 100;
  const totalAmount = billAmount + totalTip;
  const tipPerPerson = totalTip / people;
  const totalPerPerson = totalAmount / people;
  • Calculates the amounts:
    • totalTip: Calculates the total tip by multiplying the bill amount by the tip percentage and dividing by 100.
    • totalAmount: Calculates the total bill amount by adding the original bill and the total tip.
    • tipPerPerson: Divides the total tip by the number of people to get the tip amount per person.
    • totalPerPerson: Divides the total amount by the number of people to get the total amount each person needs to pay.
document.getElementById('tipAmount').textContent = `$${tipPerPerson.toFixed(2)}`;
  document.getElementById('totalAmount').textContent = `$${totalPerPerson.toFixed(2)}`;
  document.getElementById('totalBill').textContent = `$${totalAmount.toFixed(2)}`;
}
  • Updates the text content of HTML elements with IDs tipAmount, totalAmount, and totalBill to display the calculated values.
  • .toFixed(2) formats the numbers to two decimal places, ensuring they appear as currency.

2. Function: resetCalculator()

This function resets all input fields and output displays to their initial state.

Step-by-Step Explanation:

function resetCalculator() {
  • Defines the resetCalculator function.
  document.getElementById('billAmount').value = '';
  document.getElementById('tipPercent').value = '';
  document.getElementById('people').value = '';
  • Sets the values of the input fields (billAmount, tipPercent, and people) to an empty string, effectively clearing them.
  document.getElementById('tipAmount').textContent = '$0.00';
  document.getElementById('totalAmount').textContent = '$0.00';
  document.getElementById('totalBill').textContent = '$0.00';
}
  • Resets the output displays (tipAmount, totalAmount, and totalBill) to show $0.00.
function calculateTip() {
  const billAmount = parseFloat(document.getElementById('billAmount').value);
  const tipPercent = parseFloat(document.getElementById('tipPercent').value);
  const people = parseInt(document.getElementById('people').value);

  if (isNaN(billAmount) || isNaN(tipPercent) || isNaN(people) || people <= 0) {
    alert('Please enter valid inputs.');
    return;
  }

  const totalTip = (billAmount * tipPercent) / 100;
  const totalAmount = billAmount + totalTip;
  const tipPerPerson = totalTip / people;
  const totalPerPerson = totalAmount / people;

  document.getElementById('tipAmount').textContent = `$${tipPerPerson.toFixed(2)}`;
  document.getElementById('totalAmount').textContent = `$${totalPerPerson.toFixed(2)}`;
  document.getElementById('totalBill').textContent = `$${totalAmount.toFixed(2)}`;
}

function resetCalculator() {
  document.getElementById('billAmount').value = '';
  document.getElementById('tipPercent').value = '';
  document.getElementById('people').value = '';
  document.getElementById('tipAmount').textContent = '$0.00';
  document.getElementById('totalAmount').textContent = '$0.00';
  document.getElementById('totalBill').textContent = '$0.00';
}

Final Output:

easy-tip-calculator-using-html-css-and-javascript.gif

Conclusion:

You have now built your very own tip calculator using HTML, CSS, and JavaScript! This project is not only a great way to practice your coding skills but also provides a useful tool for everyday use. You can calculate tips quickly and easily, making dining out a little less stressful.

Feel free to expand on this basic calculator. You could add features like a custom tip percentage, the option to split the bill among more people, or even a reset button to clear the inputs easily. The possibilities are endless!

We hope this guide has helped you learn more about web development. Keep experimenting and building new projects. Each one will strengthen your skills and boost your confidence as a developer.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺