BMI Calculator JavaScript, HTML, CSS
👤 Sharing: AI
Okay, here's a complete HTML, CSS, and JavaScript example for a BMI (Body Mass Index) calculator. I've included explanations within the code as comments.
**HTML (index.html)**
```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="style.css"> <!-- Link to your CSS file -->
</head>
<body>
<div class="container">
<h1>BMI Calculator</h1>
<div class="input-fields">
<label for="height">Height (cm):</label>
<input type="number" id="height" placeholder="Enter height in cm">
<label for="weight">Weight (kg):</label>
<input type="number" id="weight" placeholder="Enter weight in kg">
</div>
<button id="calculate">Calculate BMI</button>
<div id="result">
<p>Your BMI is: <span id="bmi-value"></span></p>
<p id="bmi-category"></p>
</div>
</div>
<script src="script.js"></script> <!-- Link to your JavaScript file -->
</body>
</html>
```
**CSS (style.css)**
```css
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
.input-fields {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
input[type="number"] {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box; /* Important for padding and border to be included in the width */
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #3e8e41;
}
#result {
margin-top: 20px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
background-color: #f9f9f9;
}
#bmi-value {
font-weight: bold;
color: #007bff; /* Blue color for emphasis */
}
#bmi-category {
font-style: italic;
color: #777;
}
```
**JavaScript (script.js)**
```javascript
document.addEventListener('DOMContentLoaded', function() { // Ensure the DOM is fully loaded
const heightInput = document.getElementById('height');
const weightInput = document.getElementById('weight');
const calculateButton = document.getElementById('calculate');
const bmiValueDisplay = document.getElementById('bmi-value');
const bmiCategoryDisplay = document.getElementById('bmi-category');
calculateButton.addEventListener('click', function() {
// Get the height and weight values from the input fields
const height = parseFloat(heightInput.value); // Convert to a number
const weight = parseFloat(weightInput.value); // Convert to a number
// Input validation
if (isNaN(height) || isNaN(weight)) {
alert("Please enter valid numbers for height and weight.");
return; // Stop the function if input is invalid
}
if (height <= 0 || weight <= 0) {
alert("Height and weight must be positive values.");
return;
}
// Calculate BMI. Height is in cm, so convert to meters (m).
const heightInMeters = height / 100;
const bmi = weight / (heightInMeters * heightInMeters);
// Round the BMI to two decimal places
const bmiRounded = bmi.toFixed(2);
// Determine BMI category
let category = '';
if (bmi < 18.5) {
category = 'Underweight';
} else if (bmi < 25) {
category = 'Normal weight';
} else if (bmi < 30) {
category = 'Overweight';
} else {
category = 'Obese';
}
// Display the results
bmiValueDisplay.textContent = bmiRounded;
bmiCategoryDisplay.textContent = `You are ${category}.`;
});
});
```
**How to Use It**
1. **Create Files:** Create three files named `index.html`, `style.css`, and `script.js`.
2. **Copy Code:** Copy the code above into the respective files.
3. **Open in Browser:** Open `index.html` in your web browser (Chrome, Firefox, Safari, Edge, etc.).
4. **Enter Values:** Enter your height in centimeters and your weight in kilograms into the input fields.
5. **Click Calculate:** Click the "Calculate BMI" button.
6. **View Results:** The calculated BMI and your weight category will be displayed below the button.
**Key Improvements and Explanations**
* **Clearer HTML Structure:** Uses semantic HTML elements (`div`, `label`, `input`, `button`, `span`) for better structure and accessibility.
* **CSS Styling:** Provides basic CSS to make the calculator visually appealing and user-friendly. You can customize the styles further.
* **JavaScript Logic:**
* **`DOMContentLoaded`:** The JavaScript code is wrapped in a `DOMContentLoaded` event listener. This ensures that the script runs *after* the entire HTML document has been parsed and loaded. This is very important, because the JavaScript needs to be able to find the HTML elements using `document.getElementById()`.
* **Get Elements:** The code first gets references to the HTML elements that it needs to interact with (input fields, button, result display areas).
* **Event Listener:** An event listener is attached to the "Calculate BMI" button. This means that when the button is clicked, the function inside the event listener will be executed.
* **Get Input Values:** Inside the event listener, the code gets the values entered by the user from the height and weight input fields.
* **`parseFloat()`:** The `parseFloat()` function is used to convert the input values (which are strings by default) into floating-point numbers. This is necessary for performing calculations.
* **Input Validation:** The code now includes basic input validation to check if the user has entered valid numbers for height and weight. It also checks that the values are positive. If the input is invalid, an alert message is displayed, and the calculation is stopped.
* **BMI Calculation:** The BMI is calculated using the standard formula: `weight (kg) / (height (m))^2`. Note that the height is converted from centimeters to meters before the calculation.
* **`toFixed(2)`:** The `toFixed(2)` method is used to round the calculated BMI to two decimal places, making it more presentable.
* **BMI Category:** The code determines the BMI category based on the calculated BMI value.
* **Display Results:** The calculated BMI and the BMI category are displayed in the designated HTML elements. `textContent` is used to update the text content of the HTML elements.
* **Error Handling:** Includes basic error handling to catch invalid input (non-numeric values).
* **Comments:** The code is well-commented to explain each step.
* **Clear Output:** Displays both the BMI value and the BMI category.
* **Responsive Design (Basic):** The CSS includes a `viewport` meta tag to help with responsiveness on different screen sizes. You can add more advanced responsive styling as needed.
* **Accessibility:** Uses labels for input fields, which is good for accessibility.
This is a basic but functional BMI calculator. You can expand upon it by adding features like:
* Displaying a more detailed BMI chart.
* Allowing users to choose between metric and imperial units.
* Adding more advanced input validation.
* Improving the CSS styling to make the calculator more visually appealing.
* Storing previous calculations.
* Adding a graphical representation of the BMI range.
👁️ Viewed: 11
Comments