How to Create a Simple BMI Calculator with HTML, CSS, and JavaScript
Body Mass Index (BMI) is a common measure used to assess a person's healthy weight range based on their height and weight. In this tutorial, you'll learn how to construct a simple BMI calculator using HTML, CSS, and JavaScript.
Objectives
By the end of this tutorial you will have a better understanding of:
- How to use HTML to enable collection of user input.
- How to style a simple UI using CSS.
- How to get values from input fields and perform calculations using JavaScript.
Prerequisites
You will need:
- a text editor like Notepad or Visual Studio.
- a basic understanding of HTML, CSS and JavaScript.
Now lets get into it.
1. Set up the HTML Structure
Start by creating an HTML file (index.html
). The HTML's purpose is to structure the elements of the calculator:
Our BMI calculator will have the following elements:
- Heading: We will indicate the purpose of the tool with a clear heading like "BMI Calculator".
- Input Fields: We will add labeled input fields to collect the user's weight (in kilograms) and height (in centimeters).
- Button: A button will be used to trigger the calculation when clicked.
- Results Area: We will add a paragraph to display the calculated BMI and its corresponding category.
Inside the HTML file add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BMI Calculator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>BMI Calculator</h1>
<div class="calculator">
<div class="inputs">
<label for="weight">Weight (kg):</label>
<input type="number" id="weight" placeholder="Enter your weight">
<label for="height">Height (cm):</label>
<input type="number" id="height" placeholder="Enter your height">
</div>
<button onclick="calculateBMI()">Calculate BMI</button>
<div id="result"></div>
</div>
<script src="script.js"></script>
</body>
</html>
2. Style with CSS
Create a CSS file (styles.css
) to add our styling.
To enhance the user experience, we can refine the overall look and feel by styling the layout, fonts, and spacing. This includes making the input fields consistent and visually appealing, and designing a clear and inviting button that encourages users to calculate their BMI.
body {
font-family: sans-serif;
}
h1 {
text-align: center;
margin-top: 30px;
}
.calculator {
border: 1px solid #ddd;
padding: 20px;
margin: 0 auto;
max-width: 400px;
}
.inputs {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
}
input[type="number"] {
width: 100%;
padding: 8px;
box-sizing: border-box;
border: 1px solid #ccc;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#result {
margin-top: 15px;
font-weight: bold;
}
3. Implement JavaScript Functionality
Create a JavaScript file (script.js
) to handle the calculation and display of results.
To make the calculator truly interactive, let's add some behind-the-scenes magic. Here's what happens when the user clicks the "Calculate BMI" button:
- Event Listener: We attach an event listener to the 'Calculate BMI' button. This listener detects clicks and triggers a specific function to execute.
- Input Retrieval: Upon a button click, the function gathers the weight and height input values from the user.
- Validation: The function validates that the input fields are not empty. If empty, it presents an alert message to the user.
- BMI Calculation: Assuming validation passes, the function converts height from centimeters to meters for compatibility with the BMI formula. It then calculates the BMI using: BMI = weight (kg) / [height (m)]^2.
- Interpretation: The function uses a series of if-else statements to determine the BMI category based on the calculated value (underweight, normal weight, overweight, obese). It updates the designated result area with the appropriate category.
function calculateBMI() {
const weight = document.getElementById("weight").value;
const height = document.getElementById("height").value;
if (weight === "" || height === "") {
alert("Please enter both weight and height.");
return;
}
const bmi = weight / ((height / 100) * (height / 100));
let resultText = "Your BMI is: " + bmi.toFixed(1);
if (bmi < 18.5) {
resultText += " (Underweight)";
} else if (bmi >= 18.5 && bmi <= 24.9) {
resultText += " (Normal weight)";
} else if (bmi >= 25 && bmi <= 29.9) {
resultText += " (Overweight)";
} else {
resultText += " (Obese)";
}
document.getElementById("result").innerHTML = resultText;
}
This code creates a basic BMI calculator with an input for weight and height, a button to calculate the BMI, and a display area for the result. The JavaScript code retrieves the user's input, calculates the BMI, and displays the result along with a corresponding message based on the calculated value.
Our BMI calculator will look as shown below:
Conclusion
In this tutorial we covered a step-by-step approach to building a functional BMI calculator using HTML, CSS, and JavaScript. By understanding the fundamental concepts of these languages, you've gained the ability to:
- Structure the layout and content using HTML.
- Style the visual elements with CSS.
- Implement interactivity and calculations using JavaScript.
Remember, this is just the foundation. You can customize and extend your calculator further by adding features like progress bars, weight history tracking, or informative messages based on the calculated BMI. With your newfound knowledge, explore and experiment to create a unique and valuable tool for users to assess their health status.