Building a Web-Based Calorie Burn Calculator using JavaScript

Build a Calorie Burn Calculator using JavaScript

In today’s health-conscious world, understanding the calories burned during physical activities is essential for fitness enthusiasts. In this guide, we’ll walk through creating a dynamic and interactive Calorie Burn Calculator using HTML, CSS, and JavaScript. This tool allows users to estimate the calories burned based on different exercises, durations, and user weight.

Understanding the Importance of Caloric Expenditure

Before moving into the technical details, let’s explore why understanding caloric expenditure is essential. Knowing the number of calories burned during exercises helps individuals:

  • Tailor their workout routines to meet specific fitness goals.
  • Monitor and manage weight loss or gain effectively.
  • Make informed decisions about dietary choices.
Calorie Burn Calculator

Creating the HTML Structure for the Calorie Burn Calculator

The foundation of our Calorie Burn Calculator lies in the HTML structure. We create the layout, input fields, and display results within the HTML element. Clear and semantic HTML enhances accessibility and readability for a developer. Open the text editor such as VS Code or Sublime Text and create a file index.html, 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>Calorie Burn Calculator</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="calculator">
        <h1>Calorie Burn Calculator</h1>

        <label for="activity">Select Activity:</label>
        <select id="activity" name="activity">
            <!-- Populate with activity options -->
            <option value="running">Running</option>
            <option value="cycling">Cycling</option>
            <option value="swimming">Swimming</option>
            <option value="walking">Walking</option>
            <option value="aerobics">Aerobics</option>
            <option value="jumping-rope">Jumping Rope</option>
            <!-- Add more activities as needed -->
        </select>

        <br/>

        <label for="duration">Duration (minutes):</label>
        <input type="number" id="duration" name="duration" min="1" required>

        <br/>

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

        <br/>

        <button type="button" id="calculateBtn">Calculate</button>

        <hr/>

        <h4 id="result">Calories Burned: </h4>
    </div>
    <script src="calculator.js"></script>
</body>
</html>

In this example:

  • We use a <select> element for activity selection, allowing users to choose from different exercises.
  • The duration is captured using an <input type="number"> element, ensuring a numeric input for minutes.
  • User weight is also captured using another <input type="number"> element.
  • The result is displayed in a read-only <input> element.
  • A “Calculate” button triggers the calculation based on user inputs.

These input fields provide a foundation for user interaction, allowing them to input necessary details for their calorie estimation.

Styling the Calorie Burn Calculator

CSS plays a crucial role in creating an appealing and user-friendly design. By styling the calorie burn calculator, we enhance the visual experience and ensure users can easily navigate and interact with the tool. Let’s create a file style.css and add the following code:

body {
    font-family: 'Arial', sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    margin: 0;
    font-size: 17px;
    background: #fafafa;
}
h1 {
    margin: 5px 0 15px 0;
    text-align: center;
    text-transform: uppercase;
    font-size: 20px;
    letter-spacing: 1px
}
.calculator {
    width: 400px;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background: #fff;
}
label, input, button, select {
    margin: 10px 0;
}
input {
    display: block;
    width: calc(100% - 20px);
    padding: 10px;
}
select {
    display: block;
    width: 100%;
    padding: 10px;
}
button {
    background-color: #000;
    color: #fff;
    outline: 0;
    border: 0;
    padding: 10px 15px;
    cursor: pointer;
    font-size: 16px;
    margin: 0 auto; 
    border-radius: 5px;
    margin-bottom: 5px;
}
hr {
    margin: 15px 0;
}
h4 {
    margin-bottom: 0;
}

Feel free to adjust the styling of the calculator as per your design requirements.

Implementing Dynamic Functionality with JavaScript

JavaScript creates dynamic functionality in our Calorie Burn Calculator. The script calculates the calories burned based on user input and updates the result area in real time. Let’s create a new file script.js and add the following code:

// JavaScript for Calorie Burn Calculator
document.addEventListener('DOMContentLoaded', function () {
    const activitySelect = document.getElementById('activity');
    const durationInput = document.getElementById('duration');
    const weightInput = document.getElementById('weight');
    const resultInput = document.getElementById('result');
    const calculateBtn = document.getElementById('calculateBtn');

    // Event listener for calculating calories on button click
    calculateBtn.addEventListener('click', calculateCalories);

    // Function to calculate calories based on user input
    function calculateCalories() {
        const activity = activitySelect.value;
        const duration = parseFloat(durationInput.value);
        const weight = parseFloat(weightInput.value);

        if (isNaN(duration) || isNaN(weight) || duration <= 0 || weight <= 0) {
            alert('Please enter valid values for duration and weight.');
            return;
        }

        let caloriesBurned;

        // Calories calculation based on activity type (add more activities as needed)
        switch (activity) {
            case 'running':
                caloriesBurned = calculateRunningCalories(duration, weight);
                break;
            case 'cycling':
                caloriesBurned = calculateCyclingCalories(duration, weight);
                break;
            case 'swimming':
                caloriesBurned = calculateSwimmingCalories(duration, weight);
                break;
            case 'walking':
                caloriesBurned = calculateWalkingCalories(duration, weight);
                break;
            case 'aerobics':
                caloriesBurned = calculateAerobicsCalories(duration, weight);
                break;
            case 'jumping-rope':
                caloriesBurned = calculateJumpingRopeCalories(duration, weight);
                break;
            // Add more cases for additional activities
            default:
                alert('Please select a valid activity.');
                return;
        }

        // Update the result input with the calculated calories
        resultInput.innerText = `Calories Burned: ${caloriesBurned.toFixed(2)}`;
    }

    // Function to calculate calories for running (adjust the formula based on your needs)
    function calculateRunningCalories(duration, weight) {
        // Sample formula for running calories burned estimation
        const caloriesPerMinute = 0.1; // Adjust this value based on your formula
        return caloriesPerMinute * duration * weight;
    }

    // Function to calculate calories for cycling
    function calculateCyclingCalories(duration, weight) {
        // Sample formula for cycling calories burned estimation
        const caloriesPerMinute = 0.08; // Adjust this value based on your formula
        return caloriesPerMinute * duration * weight;
    }

    // Function to calculate calories for swimming
    function calculateSwimmingCalories(duration, weight) {
        // Sample formula for swimming calories burned estimation
        const caloriesPerMinute = 0.12; // Adjust this value based on your formula
        return caloriesPerMinute * duration * weight;
    }

    // Function to calculate calories for walking
    function calculateWalkingCalories(duration, weight) {
        // Sample formula for walking calories burned estimation
        const caloriesPerMinute = 0.05; // Adjust this value based on your formula
        return caloriesPerMinute * duration * weight;
    }

    // Function to calculate calories for aerobics
    function calculateAerobicsCalories(duration, weight) {
        // Sample formula for aerobics calories burned estimation
        const caloriesPerMinute = 0.07; // Adjust this value based on your formula
        return caloriesPerMinute * duration * weight;
    }

    // Function to calculate calories for jumping rope
    function calculateJumpingRopeCalories(duration, weight) {
        // Sample formula for jumping rope calories burned estimation
        const caloriesPerMinute = 0.1; // Adjust this value based on your formula
        return caloriesPerMinute * duration * weight;
    }
});

Note: Please adjust the Calorie Per Minute, guided as per your nutrition. In the example, we have taken sample values for reference.

Conclusion

Our Calorie Burn Calculator is a valuable tool for anyone aiming to maintain a healthy lifestyle. We’ve created an interactive and informative calculator by combining HTML for structure, CSS for design, and JavaScript for dynamic functionality. Understanding the code allows for customization and adaptation to specific needs. Feel free to explore the full source code and integrate this Calorie Burn Calculator into your fitness-related projects.

Remember, promoting a healthy lifestyle goes beyond the code – it’s about empowering individuals to make informed choices for their well-being.

Learn more about the Calories by clicking here.

Related Posts