jQuery TutorialsLearn to Build a Meal Tracker Using jQuery Mobile

Learn to Build a Meal Tracker Using jQuery Mobile

jQuery Mobile is a web framework also known as a mobile framework more specifically a Javascript library is developed on the basis of creating a framework which is widely compatible with a wide variety of smartphones, tablets and computers. It is also compatible with other frameworks such as PhoneGap, Worklight and more.

Some of the Features of jQuery are compatible with all major desktop and mobile platforms. A theming framework allows the creation of custom themes, limited dependencies, a codebase that scale to any screen, HTML-5 driven configuration with minimal scripting, AJAX-powered navigation with animated page transition and touch-optimized and a platform-agnostic UI widget.

In this blog, we will learn to build a simple Meal Tracker using jQuery and local storage. Local storage will allow us to save strings to local client i.e browser.

First, we will create a custom theme using the theme roller. Theme Roller is a jQuery custom theme builder to make a highly customized theme by just drag and drop colors and those themes are downloadable too.

We will apply this theme to our html file consisting of Homepage, Meal page and Add page.

index.html:

<!DOCTYPE html>
<html>
<head>
	<title>jqm_boiler</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="css/themes/mealtracker.min.css" />
<link rel="stylesheet" href="css/themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />
    <script src="js/jquery-2.2.4.min.js"></script>
    <script src="js/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
	<!-- HOMEPAGE -->
	<div data-role="page" id="home">
		<div data-role="header">
			<h1>MealTracker</h1>
			<div data-role="navbar">
				<ul>
					<li><a href="#home" data-transition="slideUp">Meals</a></li>
					<li><a href="#add" data-transition="slideUp">Add</a></li>
				</ul>
			</div>
		</div>
		<div data-role="main" class="ui-content">
			<ul id="meals" data-role="listview"></ul>
			<br><br>
			<ul id="calorieDisplay" data-role="listview"></ul>
		</div>
		<div data-role="footer" style="text-align:center">
			<p>MealTracker &copy; 2019</p>
		</div>
	</div>

	<!-- ADD PAGE -->
	<div data-role="page" id="add" data-theme="b">
		<div data-role="header">
			<h1>MealTracker</h1>
			<div data-role="navbar">
				<ul>
					<li><a href="#home" data-transition="slideUp">Meals</a></li>
					<li><a href="#add" data-transition="slideUp">Add</a></li>
				</ul>
			</div>
		</div>
		<div data-role="main" class="ui-content">
			<form id="mealForm">
				<label for="tagline">Tagline*</label>
				<input type="text" id="tagline" required>
				<label for="type">Meal Type*</label>
				<select id="type" required>
					<option value="Breakfast">Breakfast</option>
                                                           <option value="Lunch">Lunch</option>
                                                           <option value="Dinner">Dinner</option>
                                                           <option value="Snack">Snack</option>
				</select>
				<label for="date">Date*</label>
				<input type="date" id="date" required>
				<label for="calories">Calories*</label>
				<input type="text" id="calories" required>
				<label for="description">Description</label>
				<textarea id="description"></textarea>
				<input type="submit" value="Save">
			</form>
		</div>
		<div data-role="footer" style="text-align:center">
			<p>MealTracker &copy; 2019</p>
		</div>
	</div>

	<!-- MEAL PAGE -->
	<div data-role="page" id="meal">
		<div data-role="header">
			<a href="#home" class="ui-btn ui-btn-icon-left">Back</a>
			<h1>MealTracker</h1>
			<div data-role="navbar">
				<ul>
					<li><a href="#home" data-transition="slideUp">Meals</a></li>
					<li><a href="#add" data-transition="slideUp">Add</a></li>
				</ul>
			</div>
		</div>
		<div data-role="main" class="ui-content">
			<div id="mealDetails"></div>
		</div>
		<div data-role="footer" style="text-align:center">
			<p>MealTracker &copy; 2017</p>
		</div>
	</div>

	<script src="js/main.js"></script>
</body>
</html>

OUTPUT: Meals Page

Meals Page

ADD Meal Page

ADD Meal Page

We have created an outline of our Meal Tracker but it is not yet functional so that we can add, delete, save, get our meal at Local Storage as well as calculate the calorie count too.

main.js

$(document).ready(function(){
  $('#mealForm').on('submit', function(e){
    let meal = {
      id: guidGenerator(),
      tagline: $('#tagline').val(),
      type: $('#type').val(),
      date: $('#date').val(),
      calories: $('#calories').val(),
      description: $('#description').val(),
    }

    addMeal(meal);

    e.preventDefault();
  });
});

// Before Homepage Loads
$(document).on('pagebeforeshow', '#home', function(){
  getMeals();
  getCalories();
});

// Before Details Loads
$(document).on('pagebeforeshow', '#meal', function(){
  getMeal();
});

// Generate ID
function guidGenerator() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

// Save Meal to LS
function addMeal(meal){
  if(localStorage.getItem('meals') === null){
    let meals = [];
    meals.push(meal);
    localStorage.setItem('meals', JSON.stringify(meals));
  } else {
    let meals = JSON.parse(localStorage.getItem('meals'));
    meals.push(meal);
    localStorage.setItem('meals', JSON.stringify(meals));
  }
  // Clear Fields
  $('#tagline').val('');
  $('#date').val('');
  $('#calories').val('');
  $('#description').val('');
  $.mobile.changePage('#home');
}

// Get Meals From LS
function getMeals(){
  let output= '';
  if(localStorage.getItem('meals') == null || localStorage.getItem('meals') == '[]'){
    output = '<li>No Meals Found</li>';
    $('#meals').html(output).listview('refresh');
  } else{
    let meals = JSON.parse(localStorage.getItem('meals'));
    $.each(meals, function(index, meal){
      output += `
        <li>
          <a onclick="mealClicked('${meal.id}')">${meal.tagline}</a>
        </li>
      `;
    });
    $('#meals').html(output).listview('refresh');
  }
}

function mealClicked(mealId){
  sessionStorage.setItem('mealId', mealId);
  $.mobile.changePage('#meal');
}

// Get Meal Details
function getMeal(){
  if(sessionStorage.getItem('mealId') === null){
    $.mobile.changePage('#home');
  } else {
    let meals = JSON.parse(localStorage.getItem('meals'));
    $.each(meals, function(index, meal){
      if(meal.id === sessionStorage.getItem('mealId')){
        let output = `
          <h1>${meal.tagline}</h1>
          <small>${meal.type} On ${meal.date}</small>
          <p>${meal.description}</p>
          <p><strong>Calories: </strong>${meal.calories}</p>
          <button onclick="deleteMeal('${meal.id}')" class="ui-btn">Delete Meal</a>
        `;
        $('#mealDetails').html(output);
      }
    });
  }
}

// Delete Meal From LS
function deleteMeal(mealId){
  let meals = JSON.parse(localStorage.getItem('meals'));
  $.each(meals, function(index, meal){
    if(meal.id === mealId){
      meals.splice(index, 1);
    }
  });
  localStorage.setItem('meals', JSON.stringify(meals));
  $.mobile.changePage('#home');
}

// Get Calorie Count
function getCalories(){
  let output = '';
  if(localStorage.getItem('meals') === null){
    output = '<li style="text-align:center">Total Calores: 0</li>';
    $('#calorieDisplay').html(output).listview('refresh');
  } else {
    let meals = JSON.parse(localStorage.getItem('meals'));
    let calories = 0;
    $.each(meals,function(index, meal){
      calories = calories + parseInt(meal.calories);
    });
    output = '<li style="text-align:center">Total Calores: '+calories+'</li>';
    $('#calorieDisplay').html(output).listview('refresh');
  }
}

OUTPUT

Meals Page: Stored in Local Storage as seen in the URL.

Meals Page: Stored in Local Storage as seen in the URL

Add Meals

Meals Details

Meals Details

Conclusion

Either you are a gym goer or some health freak always worried about gaining weight, it is one such application which tracks the total calories consumed from any meal. Whether be it scrambled eggs or the red meat, now you can track everything with precision.

So there you go, a fully functional meal tracker is ready using jQuery mobile. In the meantime, if you are interested to learn all the details of jQuery Mobile from beginning then you can explore all the different sections of Learn jQuery Mobile from Scratch online tutorial.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -