How to Create Javascript Project a Calorie Counter Form

Tracking calorie intake is an essential step for anyone trying to maintain a healthy lifestyle. With JavaScript, you can create an interactive calorie counter form that calculates and displays the total calories consumed. Here’s a detailed guide to building this practical project:

Set Up the HTML Structure

The first step is to create a basic form where users can input food items and their calorie values. This form will serve as the foundation for our calorie counter.

HTML Code:

code<form id="calorie-calculator">
<label for="food-item">Food Item:</label>
<input type="text" id="food-item" placeholder="Enter food name"><br>

<label for="calories">Calories:</label>
<input type="number" id="calories" placeholder="Enter calories"><br>

<button type="button" onclick="addFoodItem()">Add Food</button>
<button type="button" onclick="calculateTotalCalories()">Calculate Total</button>

<h3>Food List:</h3>
<ul id="food-list"></ul>

<h3 id="result"></h3>
</form>

Add JavaScript Functionality

JavaScript is where the magic happens. It will handle input validation, store food items and calorie values, and calculate the total calories.

Get References to Elements

We first need to connect the form elements to JavaScript.

codeconst foodItemInput = document.getElementById("food-item");
const calorieInput = document.getElementById("calories");
const foodList = document.getElementById("food-list");
const resultDiv = document.getElementById("result");
let foodEntries = []; // Array to store food items and their calorie values

Add Food Items to a List

Create a function to add food items to the list. Each entry will include the food name and calorie value.

codefunction addFoodItem() {
const foodItem = foodItemInput.value;
const calories = parseInt(calorieInput.value);

// Input validation
if (!foodItem || isNaN(calories) || calories <= 0) {
alert("Please enter a valid food item and calorie value.");
return;
}

// Add food item to the array
foodEntries.push({ foodItem, calories });

// Update the food list in the UI
const listItem = document.createElement("li");
listItem.textContent = `${foodItem}: ${calories} kcal`;
foodList.appendChild(listItem);

// Clear input fields for the next entry
foodItemInput.value = "";
calorieInput.value = "";
}

Calculate Total Calories

Now, we’ll create a function to calculate the total calories from all food entries.

 codefunction calculateTotalCalories() {
let totalCalories = foodEntries.reduce((total, entry) => total + entry.calories, 0);
resultDiv.textContent = `Total Calories: ${totalCalories} kcal`;
}

Add Input Validation

Input validation is crucial to ensure users don’t leave fields empty or enter invalid data.

Example Validation Logic:

codeif (!foodItem || isNaN(calories) || calories <= 0) {
alert("Please enter a valid food item and calorie value.");
return;
}

Enhance the Application with Advanced Features

Here are some ideas to make the calorie counter more robust and user-friendly:

  • Track Progress Towards a Calorie Goal: Allow users to set a calorie goal and display progress.
codeconst calorieGoal = 2000; // Example goal
function displayProgress() {
const totalCalories = foodEntries.reduce((total, entry) => total + entry.calories, 0);
const remaining = calorieGoal - totalCalories;
if (remaining > 0) {
resultDiv.textContent = `Total Calories: ${totalCalories} kcal. You can consume ${remaining} kcal more today!`;
} else {
resultDiv.textContent = `Total Calories: ${totalCalories} kcal. You have exceeded your daily goal by ${Math.abs(remaining)} kcal.`;
}
}
  • Save Food Items: Use the browser’s local storage to save food items so users don’t lose data on page refresh.
function saveToLocalStorage() {
localStorage.setItem("foodEntries", JSON.stringify(foodEntries));
}

function loadFromLocalStorage() {
const savedEntries = JSON.parse(localStorage.getItem("foodEntries"));
if (savedEntries) {
foodEntries = savedEntries;
foodEntries.forEach(entry => {
const listItem = document.createElement("li");
listItem.textContent = `${entry.foodItem}: ${entry.calories} kcal`;
foodList.appendChild(listItem);
});
}
}

// Call loadFromLocalStorage on page load
window.onload = loadFromLocalStorage;

Style the Application

Finally, style the application for a clean and modern look.

CSS:

codeform {
max-width: 400px;
margin: 20px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
background-color: #f9f9f9;
font-family: Arial, sans-serif;
}

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

input {
width: 100%;
padding: 8px;
margin-bottom: 12px;
border: 1px solid #ccc;
border-radius: 4px;
}

button {
padding: 10px 20px;
background-color: #28a745;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
margin-right: 10px;
}

button:hover {
background-color: #218838;
}

#result {
margin-top: 20px;
font-size: 18px;
font-weight: bold;
}

Full Working Example

Here’s the complete implementation of the calorie counter:

HTML + JavaScript + CSS:

code<!DOCTYPE html>
<html>
<head>
<title>Calorie Counter</title>
<style>
/* Add CSS here */
</style>
</head>
<body>
<form id="calorie-calculator">
<label for="food-item">Food Item:</label>
<input type="text" id="food-item" placeholder="Enter food name"><br>

<label for="calories">Calories:</label>
<input type="number" id="calories" placeholder="Enter calories"><br>

<button type="button" onclick="addFoodItem()">Add Food</button>
<button type="button" onclick="calculateTotalCalories()">Calculate Total</button>

<h3>Food List:</h3>
<ul id="food-list"></ul>

<h3 id="result"></h3>
</form>

<script>
// Add JavaScript here
</script>
</body>
</html>

Conclusion

By following this guide, you can build an interactive and practical JavaScript calorie counter. This project helps reinforce core programming concepts like DOM manipulation, event handling, and input validation, while also providing a real-world use case for your skills. Customize the application further to add features like setting calorie goals or integrating a food database for a more comprehensive tool. Happy coding!

Related blog posts