Today i will create calorie tracker with pure JavaScript no library no jquery with JavaScript modular approach. Iam using material.css
Demo
html of application
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="materialize.min.css">
<title>Calorie Tracker App</title>
</head>
<body>
<nav>
<div class="nav-wrapper orange">
Track Calorie
</div>
</nav>
<div class="container">
<div class="card">
<div class="card-content">
Add Meal/Food Item
<div class="col">
<div class="row">
<div class="input-field col s6">
<input type="text" placeholder="Add Item" id="meal-name">
<label for="">Meal</label>
</div>
<div class="input-field col s6">
<input type="number" placeholder="Add Calorie" id="calorie-name">
<label for="">Calorie</label>
</div>
<button id="addMeal" class="add-btn btn blue darken-3"> Add Meal</button>
<button id="updateMeal" class="update-btn btn blue darken-3"> Updated Meal</button>
<button id="backBtn" class="back-btn btn black pull-right"> Back</button>
</div>
</div>
</div>
</div>
<h3 class="center-align">Total Calories: 0</h3>
<ul id="item-list" class="collection">
</ul>
</div>
<script src="jquery.min.js"></script>
<script src="materialize.min.js"></script>
<script src="app.js">
</script>
</body>
</html>
JavaScript of App
// CONTOLLER MODULE
var CALORIEController = (function() {
var Calorie = function(id, meal, calorie) {
this.id = id;
this.meal = meal;
this.calorie = calorie;
}
var data = {
meal: [],
currentItem: null,
total: 0
}
return {
returnTotal: function() {
var sum = 0;
data.meal.forEach(function(obj) {
sum += obj.calorie;
});
return data.total = parseInt(sum);
},
currentItemvalue: function() {
return data.currentItem;
},
updateCurrentItem: function(UpdateObj) {
var found = null;
data.meal.forEach(function(obj) {
if (obj.id == data.currentItem.id) {
obj.meal = UpdateObj.meal;
obj.calorie = parseInt(UpdateObj.calorie);
found = obj;
}
});
return found;
},
getEditItemId: function(id) {
var found = null;
data.meal.forEach(function(current) {
if (current.id == id) {
found = current;
}
});
data.currentItem = found;
return found;
},
addItem: function(meal, calorie) {
var newItem, ID;
if (data.meal.length > 0) {
ID = data.meal[data.meal.length - 1].id + 1;
} else {
ID = 0;
}
newItem = new Calorie(ID, meal, calorie);
data.meal.push(newItem);
return newItem;
},
deleteMeal: function(id) {
//alert(typeof id)
var ids, index;
ids = data.meal.map(function(current) {
return current.id;
});
index = ids.indexOf(id);
if (index !== -1) {
data.meal.splice(index, 1)
}
},
testing: function() {
console.log(data)
}
}
})();
// UI MODULE
var UIController = (function() {
var DOMString = {
mealName: '#meal-name',
calorieName: '#calorie-name',
addMealBtn: '#addMeal',
itemlist: '#item-list',
nodelist: '#item-list li',
updateMeal: '#updateMeal',
backBtn: '#backBtn',
totalSelector: '#totalCalories'
}
return {
getInput: function() {
return {
meal: document.querySelector(DOMString.mealName).value,
calorie: parseInt(document.querySelector(DOMString.calorieName).value)
}
},
totalInUI: function(totalValue) {
document.querySelector(DOMString.totalSelector).innerHTML = totalValue;
//console.log(totalValue)
},
addItem: function(obj) {
var html
//create html with placeholder
html = ' <li id="' + obj.id + '" class="collection-item">' + obj.meal + ': ' + obj.calorie + ' Calorie</li>';
//insert in DOM
document.querySelector(DOMString.itemlist).insertAdjacentHTML('beforeend', html);
},
showCleartState: function() {
document.querySelector(DOMString.updateMeal).style.display = 'none';
document.querySelector(DOMString.backBtn).style.display = 'none';
},
showEditState: function() {
document.querySelector(DOMString.updateMeal).style.display = 'inline';
document.querySelector(DOMString.backBtn).style.display = 'inline';
},
clearFields: function() {
var fields, fieldsArray;
fields = document.querySelectorAll(DOMString.mealName + ',' + DOMString.calorieName);
fieldsArray = Array.prototype.slice.call(fields);
//console.log(fieldsArray)
fieldsArray.forEach(function(current) {
current.value = "";
});
fieldsArray[0].focus();
},
deleteMealList: function(deleteId) {
document.getElementById(deleteId).remove();
},
setCurrentItem: function(currentObj) {
document.querySelector(DOMString.mealName).value = currentObj.meal;
document.querySelector(DOMString.calorieName).value = parseInt(currentObj.calorie);
},
getUpdateValue: function() {
return {
meal: document.querySelector(DOMString.mealName).value,
calorie: document.querySelector(DOMString.calorieName).value
}
},
UpdateUiValue: function() {
var updatedData, lists, id;
updatedData = CALORIEController.currentItemvalue();
//alert(typeof updatedData.calorie)
//console.log(updatedData)
//console.log(updatedData.id)
lists = document.querySelectorAll(DOMString.nodelist);
//console.log(lists)
lists = Array.from(lists);
//console.log(lists)
lists.forEach(function(list) {
id = parseInt(list.getAttribute('id'));
if (id === updatedData.id) {
//alert(typeof updatedData.calorie)
document.getElementById(updatedData.id).innerHTML = ' ' + updatedData.meal + ': ' + updatedData.calorie + ' Calorie'
}
})
//console.log(test)
},
getDOMStrings: function() {
return DOMString;
}
}
})();
// APP MODULE
var APPController = (function(CalorieCtrl, UICtrl) {
var setUpEventListner = function() {
var DOM = UICtrl.getDOMStrings();
document.querySelector(DOM.addMealBtn).addEventListener('click', ctrAddItem)
document.addEventListener('keypress', function(event) {
if (event.keyCode === 13 || event.which === 13) {
ctrAddItem();
}
});
document.querySelector(DOM.itemlist).addEventListener('click', ctrEditItem);
document.querySelector(DOM.itemlist).addEventListener('click', ctrDeleteItem);
document.querySelector(DOM.backBtn).addEventListener('click', normalState);
document.querySelector(DOM.updateMeal).addEventListener('click', ctrUpdateItem);
}
var updateUI = function() {
UICtrl.UpdateUiValue();
Materialize.toast('Meals update succssfully.', 4000);
}
var ctrUpdateItem = function() {
var inputUpdateValue;
inputUpdateValue = UICtrl.getUpdateValue();
CALORIEController.updateCurrentItem(inputUpdateValue);
//UICtrl.UpdateUiValue();
updateUI();
var total = CALORIEController.returnTotal();
UICtrl.totalInUI(total);
}
var normalState = function() {
UICtrl.showCleartState();
UICtrl.clearFields();
}
var ctrEditItem = function(event) {
//console.log(event.target);
if (event.target.classList.contains('fa-pencil')) {
var EditId, id;
id = event.target.parentNode.parentNode.id;
//console.log((parseInt(EditId));
var currentObj = CalorieCtrl.getEditItemId(id);
UICtrl.setCurrentItem(currentObj);
UICtrl.showEditState();
}
}
var ctrAddItem = function() {
//alert('add item')
var input, newMeal;
//Get input data from UIController
input = UICtrl.getInput();
if (input.meal !== "" && input.calorie !== "") {
//console.log(input)
// Add data into CALORIEController
newMeal = CalorieCtrl.addItem(input.meal, input.calorie)
//console.log(test)
UICtrl.addItem(newMeal);
//Clear fields
var total = CALORIEController.returnTotal();
//alert(typeof total)
UICtrl.totalInUI(total);
UICtrl.clearFields();
Materialize.toast('Meals added succssfully.', 4000);
} else {
Materialize.toast('All fields are required.', 4000);
}
}
var ctrDeleteItem = function(event) {
if (event.target.classList.contains('fa-remove')) {
var mealId;
mealId = event.target.parentNode.parentNode.id;
var retVal = confirm("Are you sure you want to delete this item ?");
if (retVal == true) {
if (mealId) {
//prompt()
CalorieCtrl.deleteMeal(parseInt(mealId));
UICtrl.deleteMealList(mealId);
Materialize.toast('Meals deleted succssfully.', 4000);
}
} else {
return false;
}
var total = CALORIEController.returnTotal();
//alert(typeof total)
UICtrl.totalInUI(total);
}
};
return {
init: function() {
setUpEventListner();
UICtrl.showCleartState();
console.log('App Started...')
}
}
})(CALORIEController, UIController);
APPController.init();
Unquestionably imagine that that you said. Your favorite reason seemed to be on the internet the easiest thing to bear in mind of. I say to you, I definitely get irked while people think about concerns that they plainly do not know about. You controlled to hit the nail upon the highest and also defined out the whole thing without having side effect , other folks could take a signal. Will likely be back to get more. Thank you
I feel this is one of the such a lot important info for me. And i’m happy reading your article. However should commentary on some basic things, The site taste is perfect, the articles is actually excellent : D. Good task, cheers
marydail b9c45beda1 https://coub.com/stories/2722912-episode-1-1-full-movie-online-free-quynver
nanmak b9c45beda1 https://coub.com/stories/2688095-percy-jackson-sea-of-monsters-book-chapter-3-fersony
armolw 79a0ff67a5 https://coub.com/stories/2731600-telegram-contact-dailypremiumaccountsgiveaways-watfmar
markmar 79a0ff67a5 https://coub.com/stories/2779832-writing-ethnographic-fieldnotes-chapter-1-pdf
I like the valuable info you provide in your articles. I抣l bookmark your blog and check again here frequently. I am quite certain I抣l learn a lot of new stuff right here! Best of luck for the next!
chrquin 7383628160 https://trello.com/c/xFUDhRhZ/33-epf-monthly-e-return-software-version-40-free-portable-31
jakswelb 7383628160 https://coub.com/stories/3075188-extra-quality-perkins-est-2011b-keygen-free
oaklegi 7383628160 https://trello.com/c/UV8Jd4Mz/42-zillatube-v31-2010kaiser-keygen-repack
latdarn fe98829e30 https://www.cloudschool.org/activities/ahFzfmNsb3Vkc2Nob29sLWFwcHI5CxIEVXNlchiAgIC_35WPCgwLEgZDb3Vyc2UYgICA_4SE_AgMCxIIQWN0aXZpdHkYgIDAgIufkAsMogEQNTcyODg4NTg4Mjc0ODkyOA
gabjaym fe98829e30 https://wakelet.com/wake/MkSQcyXQrjcym8_p4sbfK
opajak fe98829e30 https://trello.com/c/hoE5AZ3U/27-teksoftprocamii2006-lz0torrent-bakbetr
sarederr fe98829e30 https://www.cloudschool.org/activities/ahFzfmNsb3Vkc2Nob29sLWFwcHI5CxIEVXNlchiAgIC_vZvkCQwLEgZDb3Vyc2UYgIDAwIeXngkMCxIIQWN0aXZpdHkYgIDA0NyikgsMogEQNTcyODg4NTg4Mjc0ODkyOA
samgquan fe98829e30 https://trello.com/c/D093LYFC/22-new-neodownloader-304-crack-registration-code-full-latest
chelay fe98829e30 https://wakelet.com/wake/JFjBxHONOtNFWyZvtnNrJ
heddhea d868ddde6e https://coub.com/stories/3096503-elena-undone-2010-dvdrip-475mb
innnke d868ddde6e https://coub.com/stories/3053145-appunti-di-biochimica-piccin-pdf-15-micvyny
aleizan d868ddde6e https://coub.com/stories/3115257-free-the-call-finding-and-fulfilling-the-central-purpose-of-your-life-download-zip
valbev d868ddde6e https://coub.com/stories/3145854-_hot_-vikramadithyan-malayalam-movie-free-download-kickass-torrent
celnat d868ddde6e https://coub.com/stories/3116264-haseena-maan-jaayegi-full-movie-hd-hindi-download-fiaglyn
kaatsoff d868ddde6e https://coub.com/stories/2960778-collaboration-for-revit-2016-en-64bit-with-crack-upd-x-force
hedwalo d868ddde6e https://coub.com/stories/3117797-symantec-antivirus-v10-1-4-4010-corporate-edition-client-free-download-navamel
frytrigh d868ddde6e https://coub.com/stories/3032708-necronomicon-em-portugues-download-portable-pdf
frytrigh d868ddde6e https://coub.com/stories/3032708-necronomicon-em-portugues-download-portable-pdf
brebir d868ddde6e https://coub.com/stories/2935434-utorrent-movie-download-telugu-2016-nessam
wallhis d868ddde6e https://coub.com/stories/2943811-high-quality-midnight-autoparts-bbs
morywet d868ddde6e https://coub.com/stories/3073629-2021-klasifikasi-usia-menurut-who-pdf-download
latywil d868ddde6e https://coub.com/stories/2971296-igre-osveta-besnog-pileta-16-hetver
quyshar d868ddde6e https://coub.com/stories/3122786-steinberg-the-grand-piano-3-torrent-ozarbor
isaigene d868ddde6e https://coub.com/stories/3030798-adobe-photoshop-cc-2018-v19-1-7-x64-free-downloadl-xavdru
schaaria d868ddde6e https://coub.com/stories/3122688-new-comprender-al-ave-de-presa-nick-fox-pdf
haityba d868ddde6e https://coub.com/stories/3011024-hyderabad-nawabs-2-full-movie-free-download-in-hd-eleeglyn
quilau d868ddde6e https://coub.com/stories/3090422-red-alert-3-uprising-cd-key-crack-upd
acklfar d868ddde6e https://coub.com/stories/3032824-magenta-gold-7-2-0-by-hristoforos-extra-quality-download-pc
bailhas b7f02f1a74 https://cacmimedteguaro.wixsite.com/flimtizadisc/post/english-star-trek-beyond-4k-watch-online-dvdrip
fokkyurc b7f02f1a74 https://reappredesulz1979.wixsite.com/wijdgolpilsmon/post/photoshop-elements-12-crack-12
ofarmarl b7f02f1a74 https://maihostownneva.wixsite.com/throstebari/post/abitflashmenufullversionv150840
phiant fb158acf10 https://footcawelgarthlopn.wixsite.com/iditmaca/post/thursday-girls-more-pics-ad-pro-x32-windows-torrent-full-patch-license
mercury drug store gift certificate pharmacy club voucher code
10% OFF Voucher February 2022 for OpenMedShop openmedshop.com
is: MEDS10
kroger pharmacy discount code apollo pharmacy gift card
revigle fb158acf10 https://biorennadysre.wixsite.com/israisetag/post/f1_race_stars_pc__ita
finhart f4bc01c98b https://coub.com/stories/3365526-adobe-illustrator-photoshop-cs6-portable-error-fix-crack-top
kaajol f4bc01c98b https://coub.com/stories/3461657-tanu-weds-manu-returns-movie-in-hindi-720p-torrent-ezaphyt
ambvins f4bc01c98b https://coub.com/stories/3388026-rpes-2013-v3-download-top-torentbfdcm
annipen f4bc01c98b https://coub.com/stories/3506659-upd-adobepremiereprocc2018v120x64fullwithcracksetupfree