Comprehensive Guide to Building a BMI Calculator with JavaScript

Build a BMI Calculator with JavaScript

BMI stands for Body Mass Index. A BMI calculator is a tool that assesses an individual’s body weight with their height. It is commonly used to estimate whether a person has a healthy body weight, is underweight, overweight, or falls within the obesity range.

Introduction

Body Mass Index (BMI) is a useful metric to determine an individual’s body fat based on their weight and height. Whether you’re a health enthusiast, a web developer, or someone eager to learn, creating a BMI calculator is an excellent way to understand JavaScript’s power combined with HTML and CSS. In this article, we will walk you through creating a minimalist, efficient, and user-friendly BMI calculator.

BMI-calculator-output

How to calculate BMI?

The BMI is calculated by dividing a person’s weight in kilograms by the square of their height in meters. The result categorizes individuals into different BMI ranges, providing a general indication of their body composition and potential health risks associated with weight. BMI calculators are widely available online and are frequently used in healthcare, fitness, and wellness assessments as a quick and simple screening tool for evaluating body weight relative to height.

The formula for BMI is:

BMI Formula

What is BMI and Why is it Important?

BMI is a measure used to determine whether you have a healthy body weight for a person of your height. It’s calculated by dividing your weight in kilograms by the square of your height in meters.

The resulting value categorizes individuals as:

  • Underweight
  • Normal weight
  • Overweight
  • Obese

While BMI isn’t the sole determinant of health, it provides a helpful baseline for potential health risks associated with weight.

BMI Table

Reference: Wikipedia

Building the BMI Calculator

Structuring with HTML

This calculator will include:

  • A dropdown for gender selection.
  • Fields for weight and height (in feet and inches).
  • A button to calculate BMI.
  • A display area for the results.
<div id="calculator-container">
    <h2>BMI Calculator</h2>

    <label for="gender">Gender:</label>
    <select id="gender">
        <option value="male">Male</option>
        <option value="female">Female</option>
    </select>

    <label for="weight">Weight (kg):</label>
    <input type="number" id="weight" required>

    <label for="feet">Height (feet.inches):</label>
    <div style="display: flex; justify-content: space-between;">
        <input type="number" id="feet" placeholder="Feet" style="width: 45%;" required>
        <input type="number" id="inches" placeholder="Inches" style="width: 45%;" required>
    </div>

    <button onclick="calculateBMI()">Calculate</button>

    <div id="result"></div>
</div>

Styling with CSS

For a clean, modern look, we apply some simple styles. Remember, design plays a crucial role in user experience. Our goal is to keep it minimalist yet intuitive.

body {
    font-family: Arial, sans-serif;
    background-color: #f5f5f5;
    margin: 0;
    display: flex;
    height: 100vh;
    align-items: center;
    justify-content: center;
}

#calculator-container {
    background: #fff;
    max-width: 500px;
    padding: 30px 40px;
    border-radius: 8px;
    box-shadow: 0 3px 20px rgba(0, 0, 0, 0.1);
}

label {
    display: block;
    margin-bottom: 10px;
    font-weight: bold;
}

select, input[type="number"], button {
    width: 100%;
    padding: 10px;
    margin-bottom: 15px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 16px;
}

button {
    background-color: #007bff;
    color: white;
    border: none;
    cursor: pointer;
    transition: background-color 0.3s;
}

button:hover {
    background-color: #0056b3;
}

#result {
    padding: 20px;
    background-color: #e9f5ff;
    border-radius: 4px;
    margin-top: 20px;
}

Calculating BMI with JavaScript

As we’re dealing with height in feet and inches, we convert it to meters. Our JavaScript function will handle this conversion, compute the BMI, determine the weight category, and also provide the ideal weight based on gender.

function calculateBMI() {
    const weight = parseFloat(document.getElementById('weight').value);
    const feet = parseFloat(document.getElementById('feet').value);
    const inches = parseFloat(document.getElementById('inches').value);
    const gender = document.getElementById('gender').value;

    if (isNaN(weight) || isNaN(feet) || isNaN(inches)) {
        alert('Please enter valid values for weight, feet, and inches.');
        return;
    }

    const totalHeightInInches = (feet * 12) + inches;
    const heightInMeters = totalHeightInInches * 0.0254; 

    const bmi = (weight / (heightInMeters * heightInMeters)).toFixed(2);

    let status = '';
    if (bmi < 18.5) {
        status = 'Underweight';
    }
    else if (bmi >= 18.5 && bmi <= 24.9) {
        status = 'Normal weight';
    }
    else if (bmi >= 25 && bmi <= 29.9) {
        status = 'Overweight';
    }
    else if (bmi >= 30 && bmi <= 34.9) {
        status = 'Moderately Overweight';
    }
    else if (bmi >= 35 && bmi <= 39.9) {
        status = 'Severely Overweight';
    } 
    else {
        status = 'Morbidly Overweight';
    }

    let idealWeight = 0;
    if (gender === 'male') {
        idealWeight = (50 + 2.3 * (totalHeightInInches - 60)).toFixed(2);
    } else {
        idealWeight = (45.5 + 2.3 * (totalHeightInInches - 60)).toFixed(2);
    }

    document.getElementById('result').innerHTML = 
        `<strong>Your BMI:</strong> ${bmi} <br> 
        <strong>Weight Status:</strong> ${status} <br>
        <strong>Ideal BMI:</strong> 18.5 - 24.9 <br>
        <strong>Ideal Weight for ${gender.charAt(0).toUpperCase() + gender.slice(1)}:</strong> ${idealWeight} kg`;
}

The full code for BMI Calculator

Here we go with the full 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>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            display: flex;
            height: 100vh;
            align-items: center;
            justify-content: center;
        }

        #calculator-container {
            background: #fff;
            max-width: 500px;
            padding: 30px 40px;
            border-radius: 8px;
            box-shadow: 0 3px 20px rgba(0, 0, 0, 0.1);
        }

        label {
            display: block;
            margin-bottom: 10px;
            font-weight: bold;
        }

        select, input[type="number"], button {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            font-size: 16px;
        }

        button {
            background-color: #007bff;
            color: white;
            border: none;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #0056b3;
        }

        #result {
            padding: 20px;
            background-color: #e9f5ff;
            border-radius: 4px;
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <div id="calculator-container">
        <h2>BMI Calculator</h2>

        <label for="gender">Gender:</label>
        <select id="gender">
            <option value="male">Male</option>
            <option value="female">Female</option>
        </select>

        <label for="weight">Weight (kg):</label>
        <input type="number" id="weight" required>

        <label for="feet">Height (feet.inches):</label>
        <div style="display: flex; justify-content: space-between;">
            <input type="number" id="feet" placeholder="Feet" style="width: 45%;" required>
            <input type="number" id="inches" placeholder="Inches" style="width: 45%;" required>
        </div>

        <button onclick="calculateBMI()">Calculate</button>

        <div id="result"></div>
    </div>

    <script>
        function calculateBMI() {
            const weight = parseFloat(document.getElementById('weight').value);
            const feet = parseFloat(document.getElementById('feet').value);
            const inches = parseFloat(document.getElementById('inches').value);
            const gender = document.getElementById('gender').value;

            if (isNaN(weight) || isNaN(feet) || isNaN(inches)) {
                alert('Please enter valid values for weight, feet, and inches.');
                return;
            }

            const totalHeightInInches = (feet * 12) + inches;
            const heightInMeters = totalHeightInInches * 0.0254; 

            const bmi = (weight / (heightInMeters * heightInMeters)).toFixed(2);

            let status = '';
            if (bmi < 18.5) {
                status = 'Underweight';
            }
            else if (bmi >= 18.5 && bmi <= 24.9) {
                status = 'Normal weight';
            }
            else if (bmi >= 25 && bmi <= 29.9) {
                status = 'Overweight';
            }
            else if (bmi >= 30 && bmi <= 34.9) {
                status = 'Moderately Overweight';
            }
            else if (bmi >= 35 && bmi <= 39.9) {
                status = 'Severely Overweight';
            } 
            else {
                status = 'Morbidly Overweight';
            }

            let idealWeight = 0;
            if (gender === 'male') {
                idealWeight = (50 + 2.3 * (totalHeightInInches - 60)).toFixed(2);
            } else {
                idealWeight = (45.5 + 2.3 * (totalHeightInInches - 60)).toFixed(2);
            }

            document.getElementById('result').innerHTML = 
                `<strong>Your BMI:</strong> ${bmi} <br> 
                <strong>Weight Status:</strong> ${status} <br>
                <strong>Ideal BMI:</strong> 18.5 - 24.9 <br>
                <strong>Ideal Weight for ${gender.charAt(0).toUpperCase() + gender.slice(1)}:</strong> ${idealWeight} kg`;
        }
    </script>
</body>
</html>

Conclusion

Building a BMI calculator offers more than just a practical application. It’s a valuable exercise in understanding user input, processing data, and presenting results in a meaningful manner. As with all web development projects, you can continually refine, adding features like visual charts, integration with fitness APIs, or even a history tracker.

Remember, while BMI is a good starting point, always consult with healthcare professionals for a comprehensive understanding of health.

Related Posts