Introduction
In this tutorial, we will learn how to create a simple BMI (Body Mass Index) calculator using HTML, CSS, and JavaScript. This tool allows users to input their weight and height, calculate their BMI, and understand what that means for their health.
What is BMI?
Body Mass Index (BMI) is a numerical value derived from a person’s weight and height. It is used to categorize individuals into different weight categories: underweight, normal weight, overweight, and obese. Understanding your BMI can help you make informed health decisions.
Project Overview
Tools Needed
- HTML for the structure of the calculator
- CSS for styling
- JavaScript for the functionality
index.html
<!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="styles.css">
</head>
<body>
<div class="container">
<h1>BMI Calculator</h1>
<!-- BMI Input Form -->
<div class="form-group">
<label for="weight">Weight (kg):</label>
<input type="number" id="weight" placeholder="Enter weight in kg" required>
</div>
<div class="form-group">
<label for="height">Height (cm):</label>
<input type="number" id="height" placeholder="Enter height in cm" required>
</div>
<button onclick="calculateBMI()">Calculate BMI</button>
<p id="bmiResult"></p>
<p id="category"></p>
</div>
<script src="script.js"></script>
</body>
</html>
styles.css
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 400px;
text-align: center;
}
h1 {
color: #333;
margin-bottom: 20px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
font-size: 1rem;
margin-bottom: 5px;
color: #555;
}
input {
width: 100%;
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1rem;
box-sizing: border-box;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
font-size: 1rem;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
p {
font-size: 1.2rem;
font-weight: bold;
color: #333;
margin-top: 10px;
}
script.js
function calculateBMI() {
// Get the weight and height input values
const weight = parseFloat(document.getElementById('weight').value);
const height = parseFloat(document.getElementById('height').value);
// Check if the input values are valid
if (isNaN(weight) || weight <= 0 || isNaN(height) || height <= 0) {
document.getElementById('bmiResult').textContent = "Please enter valid weight and height.";
document.getElementById('category').textContent = "";
return;
}
// Convert height from cm to meters
const heightInMeters = height / 100;
// Calculate BMI: BMI = weight (kg) / height (m)^2
const bmi = weight / (heightInMeters * heightInMeters);
// Round the result to 2 decimal places
const roundedBMI = bmi.toFixed(2);
// Display the BMI result
document.getElementById('bmiResult').textContent = `Your BMI is: ${roundedBMI}`;
// Determine the BMI category
let category = "";
if (bmi < 18.5) {
category = "You are underweight.";
} else if (bmi >= 18.5 && bmi < 24.9) {
category = "You have a normal weight.";
} else if (bmi >= 25 && bmi < 29.9) {
category = "You are overweight.";
} else {
category = "You are obese.";
}
// Display the category
document.getElementById('category').textContent = category;
}
Let’s break down the calculateBMI
function step by step to understand how it works and what each part of the code does:
1. Getting User Input (Weight and Height)
javascriptCopy codeconst weight = parseFloat(document.getElementById('weight').value);
const height = parseFloat(document.getElementById('height').value);
document.getElementById('weight').value
: This retrieves the value from the HTML input field with theid="weight"
. The value entered by the user is a string, so we useparseFloat
to convert it to a floating-point number.document.getElementById('height').value
: Similarly, this retrieves the value from the height input field and converts it to a number.
These values represent the weight in kilograms and height in centimeters that the user enters.
2. Validating Input Values
javascriptCopy codeif (isNaN(weight) || weight <= 0 || isNaN(height) || height <= 0) {
document.getElementById('bmiResult').textContent = "Please enter valid weight and height.";
document.getElementById('category').textContent = "";
return;
}
isNaN(weight)
: TheisNaN
function checks if the weight is a valid number. If it’s not a valid number (e.g., if the user entered something that can’t be converted to a number), this will returntrue
.weight <= 0
: Checks if the weight is less than or equal to 0. Since weight must be a positive number, this ensures that invalid inputs like 0 or negative numbers are rejected.isNaN(height)
: Similar check for the height to ensure it’s a valid number.height <= 0
: Ensures that height is a positive number. Height in centimeters can’t be zero or negative, so this condition catches such cases.
If any of these conditions are met (invalid weight or height), the function displays an error message: “Please enter valid weight and height.” and clears the category field (because BMI can’t be calculated). The function then returns early and stops further execution.
3. Converting Height to Meters
javascriptCopy codeconst heightInMeters = height / 100;
- Since the height is given in centimeters, we need to convert it to meters before performing the BMI calculation.
- The conversion is done by dividing the height in centimeters by 100. For example, if the height is 170 cm, it will be converted to 1.7 meters.
4. Calculating BMI
javascriptCopy codeconst bmi = weight / (heightInMeters * heightInMeters);
- The formula for calculating BMI (Body Mass Index) is:BMI=weight (kg)height (m)2\text{BMI} = \frac{\text{weight (kg)}}{\text{height (m)}^2}BMI=height (m)2weight (kg)
- The heightInMeters is squared (
heightInMeters * heightInMeters
) and then the weight is divided by the squared height to calculate the BMI.
5. Rounding the BMI Result
javascriptCopy codeconst roundedBMI = bmi.toFixed(2);
bmi.toFixed(2)
: This rounds the BMI value to two decimal places for better readability. For example, if the BMI is 23.456, it will be rounded to23.46
.
6. Displaying the BMI Result
javascriptCopy codedocument.getElementById('bmiResult').textContent = `Your BMI is: ${roundedBMI}`;
- The
textContent
of the HTML element with the idbmiResult
is updated to display the calculated BMI value. It will show something like: “Your BMI is: 23.46”.
7. Determining the BMI Category
javascriptCopy codelet category = "";
if (bmi < 18.5) {
category = "You are underweight.";
} else if (bmi >= 18.5 && bmi < 24.9) {
category = "You have a normal weight.";
} else if (bmi >= 25 && bmi < 29.9) {
category = "You are overweight.";
} else {
category = "You are obese.";
}
- This block of code evaluates the calculated BMI and assigns a corresponding category.
- Underweight: BMI less than 18.5.
- Normal weight: BMI between 18.5 and 24.9.
- Overweight: BMI between 25 and 29.9.
- Obese: BMI of 30 or higher.
Based on the BMI, a message like “You are underweight”, “You have a normal weight”, etc., is stored in the category
variable.
8. Displaying the BMI Category
javascriptCopy codedocument.getElementById('category').textContent = category;
- The
textContent
of the HTML element with the idcategory
is updated to show the appropriate category message (e.g., “You are underweight” or “You are obese”).
Summary of the Flow:
- The function retrieves the weight and height values from the user input.
- It checks if the inputs are valid numbers and positive values.
- Converts the height from centimeters to meters.
- Calculates the BMI using the formula.
- Rounds the BMI to two decimal places.
- Displays the BMI result.
- Determines the BMI category (e.g., underweight, normal weight, overweight, obese).
- Displays the corresponding category message.
Example Scenario:
- Input: Weight = 70 kg, Height = 175 cm
- Conversion: Height = 175 cm / 100 = 1.75 meters
- BMI Calculation: BMI = 70 / (1.75 * 1.75) = 22.86
- Category: “You have a normal weight.”
The result will be displayed as:
- “Your BMI is: 22.86”
- “You have a normal weight.”
Conclusion:
This function is a simple way to calculate the Body Mass Index (BMI) based on user input for weight and height. It also classifies the BMI into categories (underweight, normal, overweight, obese) and displays the result on the page. The function validates input, performs the necessary calculation, and then updates the page with the calculated BMI and its category.