Creating a BMI and Caloric Needs Calculator Using JavaScript with code

Introduction

In today's world, staying fit and healthy has become a priority for many individuals. With the rise of fitness apps and online health resources, personalized workout plans are more accessible than ever. But what if you could create a simple yet effective fitness tracker that calculates your Body Mass Index (BMI) and suggests workout routines based on your activity level, age, and other parameters? In this article, we'll walk through building a fitness tracker web application using HTML, CSS, and JavaScript.

What You’ll Need?

Before diving into the code, let's review the basic technologies we'll be using.

  • HTML: To structure the page and collect user input (age, weight, height, gender, and activity level).
  • CSS: To style the page and make it visually appealing.
  • JavaScript: To handle user input, calculate BMI and daily caloric needs, and suggest workouts based on the data.

Let’s dive into the step-by-step process of building our Fitness Tracker web application, starting with the HTML structure and followed by styling with CSS and adding functionality using JavaScript.

Step 1. HTML Structure

The HTML layout is simple yet effective. The user is prompted to enter their age, weight, height, gender, and activity level, which are essential to calculate personalized workout recommendations.

Here's the HTML structure for gathering user input.

<body>
    <div class="container">
        <h1>Fitness Tracker App</h1>
        <h2>Enter Your Details</h2>

        <form id="fitnessForm">
            <input type="number" id="age" placeholder="Enter Your Age" required>
            <input type="number" id="weight" placeholder="Weight in kg" required>
            <input type="number" id="feet" placeholder="Height (Feet)" required>
            <input type="number" id="inches" placeholder="Height (Inches)" required>

            <select id="gender" required>
                <option value="" disabled selected>Gender</option>
                <option value="male">Male</option>
                <option value="female">Female</option>
            </select>

            <select id="activityLevel" required>
                <option value="" disabled selected>Activity Level</option>
                <option value="sedentary">Sedentary (little or no exercise)</option>
                <option value="light">Lightly active (light exercise or sports 1-3 days/week)</option>
                <option value="moderate">Moderately active (moderate exercise or sports 3-5 days/week)</option>
                <option value="active">Very active (hard exercise or sports 6-7 days/week)</option>
            </select>

            <button type="submit">Get Workout Recommendation</button>
        </form>

        <div class="result" id="recommendation" style="display:none;">
            <h3>Your Recommended Workout:</h3>
            <p id="workoutType"></p>
            <p id="bmiValue"></p>
            <p id="caloricNeeds"></p>
        </div>
    </div>
</body>

Step 2. CSS Styling

The CSS ensures that the app looks modern and user-friendly. A gradient background adds a touch of aesthetic appeal, while the form elements are styled to be clean and consistent. Here's the main styling.

<style>
    /* Ensure both html and body take up the full height */
    html,
    body {
        height: 100%; /* Full height */
        margin: 10px; /* Remove default margin */
    }
    body {
        font-family: Arial, sans-serif;
        background: linear-gradient(rgb(111, 113, 233), rgb(21, 21, 21)); /* Gradient background */
        color: #ffffff;
        text-align: center;
        padding: 20px;
    }
    .container {
        max-width: 600px;
        margin: 0 auto;
    }
    h1,
    h2 {
        margin-bottom: 20px;
    }
    input,
    button,
    select {
        padding: 10px;
        margin: 5px 0;
        border-radius: 5px;
        border: none;
        width: 300px; /* Fixed width for all elements */
        font-size: 16px;
        box-sizing: border-box; /* Ensure padding and border are included in width */
    }
    button {
        background-color: #ff416c;
        color: white;
        cursor: pointer;
    }
    .result {
        margin-top: 20px;
        padding: 15px;
        background-color: #1e1e1e;
        border-radius: 5px;
    }
    .result p {
        margin: 5px 0;
    }
</style>

Step 3. JavaScript Logic

The core functionality of the app lies in JavaScript. When the user submits their data, the script calculates BMI, adjusts caloric needs based on activity level, and provides workout suggestions accordingly. Here's a summary of the important steps.

  • Convert Height to Centimeters: Since height is entered in feet and inches, the script converts it into centimeters to make calculations easier.
  • Calculate BMI: The formula for BMI is weight / height², with height in meters.
  • Calculate BMR: The Basal Metabolic Rate (BMR) is calculated using the Mifflin-St Jeor Equation, which differs for males and females.
  • Adjust for Activity Level: The activity level multiplier is applied to BMR to calculate the daily caloric needs.
  • Workout Recommendations: Based on age, BMI, and activity level, a personalized workout suggestion is generated.

Here’s how the JavaScript handles these calculations.

<script>
    document.getElementById('fitnessForm').addEventListener('submit', function (event) {
        event.preventDefault();

        const age = parseInt(document.getElementById('age').value);
        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;
        const activityLevel = document.getElementById('activityLevel').value;

        // Convert feet and inches to centimeters
        const heightInCm = (feet * 30.48) + (inches * 2.54);

        // Calculate BMI
        const bmi = (weight / ((heightInCm / 100) * (heightInCm / 100))).toFixed(1);

        // Calculate BMR (Mifflin-St Jeor Equation)
        let bmr;
        if (gender === 'male') {
            bmr = 10 * weight + 6.25 * heightInCm - 5 * age + 5;
        } else if (gender === 'female') {
            bmr = 10 * weight + 6.25 * heightInCm - 5 * age - 161;
        }

        // Adjust BMR based on activity level
        let activityMultiplier;
        switch (activityLevel) {
            case 'sedentary': activityMultiplier = 1.2; break;
            case 'light': activityMultiplier = 1.375; break;
            case 'moderate': activityMultiplier = 1.55; break;
            case 'active': activityMultiplier = 1.725; break;
        }

        const dailyCaloricNeeds = (bmr * activityMultiplier).toFixed(0);

        // Determine workout recommendation based on age and BMI
        let workoutRecommendation = '';

        if (age < 18) {
            workoutRecommendation = "Since you're under 18, we recommend light exercises like Yoga or Stretching.";
        } else if (age >= 18 && age <= 40) {
            if (bmi < 18.5) {
                workoutRecommendation = `Your BMI is ${bmi}. You're underweight. Strength Training can help you build muscle.`;
            } else if (bmi >= 18.5 && bmi <= 24.9) {
                workoutRecommendation = `Your BMI is ${bmi}. You have a normal weight. A balanced Cardio and Strength Training routine is recommended.`;
            } else {
                workoutRecommendation = `Your BMI is ${bmi}. You're overweight. Focus on Cardio to burn fat.`;
            }
        } else {
            if (bmi < 18.5) {
                workoutRecommendation = `Your BMI is ${bmi}. You're underweight. Light Strength Training and Yoga can help.`;
            } else if (bmi >= 18.5 && bmi <= 24.9) {
                workoutRecommendation = `Your BMI is ${bmi}. You have a normal weight. Consider walking, swimming, or light strength exercises.`;
            } else {
                workoutRecommendation = `Your BMI is ${bmi}. You're overweight. Low-impact cardio like walking or swimming is ideal.`;
            }
        }

        // Display the recommendation along with calculated values
        document.getElementById('workoutType').innerText = workoutRecommendation;
        if (bmi > 0 && bmi <= 100) {
            document.getElementById('bmiValue').innerText = `Your BMI is: ${bmi}`;
            document.getElementById('caloricNeeds').innerText = `Your Daily Caloric Needs: ${dailyCaloricNeeds} kcal`;
        }
        document.getElementById('recommendation').style.display = 'block';
    });
</script>

Step 4. Displaying Results

Once the form is submitted, the app displays the workout recommendation, the user’s BMI, and their daily caloric needs. The result is shown in a neat card with a dark background to emphasize the information.

Output

Fitness tracker

Conclusion

This fitness tracker project showcases how HTML, CSS, and JavaScript can work together to create a user-friendly app that calculates BMI and daily caloric needs and provides personalized workout recommendations, making fitness more accessible and engaging.