update,
This commit is contained in:
456
givefortune/task1/source/u-QhJMXmcPK/index.js
Normal file
456
givefortune/task1/source/u-QhJMXmcPK/index.js
Normal file
@@ -0,0 +1,456 @@
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
var healthForm = document.getElementById("healthForm");
|
||||
var submitBtn = document.getElementById("submitBtn");
|
||||
var questionContainer = document.getElementById("questionContainer");
|
||||
var resultBmr = document.getElementById("result");
|
||||
var calValue = document.getElementById("cal-value");
|
||||
var calValueText = document.createElement("h1");
|
||||
// var part2Result = document.getElementById("part2result");
|
||||
var resultContainer = document.getElementById("result-container");
|
||||
var caloriesRecord = document.createElement("div");
|
||||
var goalChoice = document.getElementsByName("goal_weight");
|
||||
var formTitle = document.getElementById("form-title");
|
||||
var barChartContainer = document.getElementById("container");
|
||||
|
||||
//input value
|
||||
|
||||
//var dailyCalorie = document.getElementsByClassName("part3");
|
||||
|
||||
//calculate bmr
|
||||
function bmrFunction() {
|
||||
var age = document.getElementById("ageInput").value;
|
||||
var gender = document.getElementById("genderInput").value;
|
||||
var height = document.getElementById("heightInput").value;
|
||||
var weight = document.getElementById("weightInput").value;
|
||||
var activityLevel = document.getElementById("activityLevelInput").value;
|
||||
|
||||
var genderMultiplier = 0;
|
||||
if (gender === "male") {
|
||||
genderMultiplier = 1;
|
||||
}
|
||||
|
||||
var activityLevelMultiplier = 0;
|
||||
if (activityLevel === "sedentary") {
|
||||
activityLevelMultiplier = 1.2;
|
||||
} else if (activityLevel === "lightlyActive") {
|
||||
activityLevelMultiplier = 1.375;
|
||||
} else if (activityLevel === "moderatelyActive") {
|
||||
activityLevelMultiplier = 1.55;
|
||||
} else if (activityLevel === "veryActive") {
|
||||
activityLevelMultiplier = 1.72;
|
||||
} else if (activityLevel === "superActive") {
|
||||
activityLevelMultiplier = 1.9;
|
||||
}
|
||||
|
||||
const result =
|
||||
9.99 * weight +
|
||||
6.25 * height -
|
||||
4.92 * age +
|
||||
(166 * genderMultiplier - 161);
|
||||
|
||||
const bmrresult = result * activityLevelMultiplier;
|
||||
return bmrresult;
|
||||
}
|
||||
|
||||
//submit bmr form and click function
|
||||
healthForm.addEventListener("submit", function (event) {
|
||||
event.preventDefault();
|
||||
var name = document.getElementById("nameInput").value;
|
||||
var resultBmr = document.getElementById("result");
|
||||
var age = document.getElementById("ageInput").value;
|
||||
var gender = document.getElementById("genderInput").value;
|
||||
var height = document.getElementById("heightInput").value;
|
||||
var weight = document.getElementById("weightInput").value;
|
||||
var activityLevel = document.getElementById("activityLevelInput").value;
|
||||
|
||||
resultBmr.innerHTML = ""; // 清空结果元素的内容
|
||||
formTitle.innerHTML = "";
|
||||
|
||||
var resultText = document.createElement("h3");
|
||||
resultText.innerHTML = `<p>Hello! ${name}.</p>
|
||||
<p>Your daily calorie intake: </p>
|
||||
<div id="intake-contain"></div>
|
||||
<button id="edit">Edit & Calculate again</button>
|
||||
|
||||
<div class="threeBtn">
|
||||
<form>
|
||||
<p>Which goal would you like to achieve?</p>
|
||||
<input type="radio" id="maintain" name="goal_weight" value="maintain-weight">
|
||||
<label for="html">Maintain Weight (+- 0cal)</label><br>
|
||||
<input type="radio" id="loss" name="goal_weight" value="loss-weight">
|
||||
<label for="css">Loss Weight (- 300cals)</label><br>
|
||||
<input type="radio" id="gain" name="goal_weight" value="gain-weight">
|
||||
<label for="javascript">Gain Weight (+ 300cals)</label></form>
|
||||
</div>
|
||||
<div id="saveBtn-contain"></div>
|
||||
`;
|
||||
resultBmr.appendChild(resultText);
|
||||
healthForm.style.display = "none";
|
||||
|
||||
const intakeContain = document.getElementById("intake-contain");
|
||||
const intakeNum = document.createElement("h2");
|
||||
intakeNum.innerText = `${Math.round(bmrFunction())}cal`;
|
||||
intakeContain.appendChild(intakeNum);
|
||||
|
||||
localStorage.setItem("user", name);
|
||||
localStorage.setItem("userAge", age);
|
||||
localStorage.setItem("userGender", gender);
|
||||
localStorage.setItem("userHeight", height);
|
||||
localStorage.setItem("userWeight", weight);
|
||||
localStorage.setItem("userActivityLevel", activityLevel);
|
||||
localStorage.setItem("bmrResult", bmrFunction());
|
||||
|
||||
// localStorage.getItem("user");
|
||||
// JSON.parse(localStorage.getItem("userAge"));
|
||||
// JSON.parse(localStorage.getItem("userGender"));
|
||||
// JSON.parse(localStorage.getItem("userHeight"));
|
||||
// JSON.parse(localStorage.getItem("userWeight"));
|
||||
// JSON.parse(localStorage.getItem("userActivityLevel"));
|
||||
// JSON.parse(localStorage.getItem("bmrResult"));
|
||||
|
||||
function btn1() {
|
||||
//var maintainWeight = document.getElementById("maintain-weight");
|
||||
return (intakeNum.innerText = `${Math.round(bmrFunction())}cal`);
|
||||
}
|
||||
|
||||
function btn2() {
|
||||
//var lossWeight = document.getElementById("loss-weight");
|
||||
return (intakeNum.innerText = `${Math.round(bmrFunction()) - 300}cal`);
|
||||
}
|
||||
|
||||
function btn3() {
|
||||
//var gainWeight = document.getElementById("gain-weight");
|
||||
return (intakeNum.innerText = `${Math.round(bmrFunction()) + 300}cal`);
|
||||
}
|
||||
|
||||
var editBtn = document.getElementById("edit");
|
||||
editBtn.addEventListener("click", function clickFn() {
|
||||
healthForm.style.display = "block";
|
||||
resultBmr.style.display = "none";
|
||||
resultText.innerHTML = "";
|
||||
});
|
||||
|
||||
var maintainWeight = document.getElementById("maintain");
|
||||
maintainWeight.addEventListener("click", btn1);
|
||||
|
||||
var lossWeight = document.getElementById("loss");
|
||||
lossWeight.addEventListener("click", btn2);
|
||||
|
||||
var gainWeight = document.getElementById("gain");
|
||||
gainWeight.addEventListener("click", btn3);
|
||||
|
||||
var goalvalue;
|
||||
|
||||
for (var i = 0; i < goalChoice.length; i++) {
|
||||
goalChoice[i].addEventListener("click", function () {
|
||||
if (this.value === "maintain-weight") {
|
||||
goalvalue = Math.round(bmrFunction()) + 0;
|
||||
} else if (this.value === "loss-weight") {
|
||||
goalvalue = Math.round(bmrFunction()) - 300;
|
||||
} else if (this.value === "gain-weight") {
|
||||
goalvalue = Math.round(bmrFunction()) + 300;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
var saveBtnContain = document.getElementById("saveBtn-contain");
|
||||
var saveBtn = document.createElement("button");
|
||||
saveBtn.innerText = "Save";
|
||||
saveBtn.id = "saveBtn";
|
||||
saveBtnContain.appendChild(saveBtn);
|
||||
saveBtn.addEventListener("click", function () {
|
||||
resultText.innerHTML = `<p>Your daily calorie intake: </p>
|
||||
<h2>${goalvalue}cals</h2>
|
||||
<button id="edittwo">Edit & Calculate again</button>
|
||||
`;
|
||||
calValueText.innerText = `${goalvalue}cal`;
|
||||
calValue.appendChild(calValueText);
|
||||
});
|
||||
|
||||
var editBtnTwo = document.getElementById("edittwo");
|
||||
editBtnTwo.addEventListener("click", function clickFn() {
|
||||
healthForm.style.display = "block";
|
||||
calValue.style.display = "none";
|
||||
resultText.innerHTML = "";
|
||||
});
|
||||
});
|
||||
|
||||
// Clear input fields
|
||||
// document.getElementById("ageInput").value = "";
|
||||
// document.getElementById("heightInput").value = "";
|
||||
// document.getElementById("weightInput").value = "";
|
||||
|
||||
//Hide form and show question
|
||||
|
||||
questionContainer.style.display = "block";
|
||||
|
||||
// foodSubmitBtn.addEventListener("click", function () {
|
||||
// var foodIntake = foodInput.value;
|
||||
|
||||
// // Clear input field
|
||||
// foodInput.value = "";
|
||||
|
||||
// // Process food intake data
|
||||
// console.log("Food Intake:", foodIntake);
|
||||
// });
|
||||
|
||||
// function addFoodCa(x, y) {
|
||||
// var calBar = document.createElement("div");
|
||||
// calBar.classList.add("calBar");
|
||||
// calBar.innerHTML = `<div>${x}</div><div>${y}</div>`;
|
||||
// caloriesRecord.appendChild(calBar);
|
||||
// }
|
||||
|
||||
//calculate food calorie
|
||||
const calculateBtn = document.getElementById("calculate-btn");
|
||||
calculateBtn.addEventListener("click", fetchData);
|
||||
|
||||
async function fetchData() {
|
||||
const foodWeightInput = document.getElementById("food-weight-input");
|
||||
const unitSelect = document.getElementById("unit-select");
|
||||
const foodNameInput = document.getElementById("food-name-input");
|
||||
|
||||
const query = `${foodWeightInput.value}${unitSelect.value} ${foodNameInput.value}`;
|
||||
|
||||
try {
|
||||
const res = await fetch(
|
||||
"https://api.api-ninjas.com/v1/nutrition?query=" + query,
|
||||
{
|
||||
headers: {
|
||||
"X-Api-Key": "HQR305Z28JdtTlSD7bzr2g==syWXu3chI7wcfy3N",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}
|
||||
);
|
||||
const data = await res.json();
|
||||
console.log(data);
|
||||
|
||||
resultContainer.innerHTML = "";
|
||||
|
||||
// Display the data in the result container
|
||||
var foodResultText = document.createElement("div");
|
||||
foodResultText.className = "foodresult";
|
||||
foodResultText.innerHTML = `
|
||||
<h2>Results:</h2>
|
||||
<div class="line" id="foodname">Name: ${data[0].name}</div>
|
||||
<div class="line" id="serving_size">Serving Size: ${data[0].serving_size_g}g</div>
|
||||
<div class="line" id="calories">Calories: ${data[0].calories} cal</div>
|
||||
<div class="line" >Protein: ${data[0].protein_g} g</div>
|
||||
<div class="line" >Fiber: ${data[0].fiber_g} g</div>
|
||||
<div class="line" >Total Fat: ${data[0].fat_total_g} g</div>
|
||||
<div class="line" >Saturated Fat: ${data[0].fat_saturated_g} g</div>
|
||||
<div class="line" >Cholesterol: ${data[0].cholesterol_mg} g</div>
|
||||
<div class="line" >Total Carbohydrates: ${data[0].carbohydrates_total_g} g</div>
|
||||
<button id="recordbtn">Save in the intake list</button>
|
||||
`;
|
||||
|
||||
resultContainer.appendChild(foodResultText);
|
||||
|
||||
foodWeightInput.value = "";
|
||||
|
||||
foodNameInput.value = "";
|
||||
|
||||
var part2Result = document.getElementById("part2Result");
|
||||
|
||||
var recordbtn = document.getElementById("recordbtn");
|
||||
recordbtn.addEventListener("click", function clickFn() {
|
||||
//part2Result.style.backgroundColor = "#c7a5fa";
|
||||
foodResultText.style.display = "none";
|
||||
|
||||
caloriesRecord.className = "calorierecord";
|
||||
caloriesRecord.innerHTML = `
|
||||
<button id="back">Back</button>
|
||||
<h3>Calories Tracking Record</h3>
|
||||
<div class="recorddate"></div><br>
|
||||
<div class="nameCal">
|
||||
<div>Name</div>
|
||||
<div>Calories</div>
|
||||
</div>
|
||||
`;
|
||||
foodIntakeRecording(data[0].name, data[0].calories);
|
||||
sumUp();
|
||||
//localStorage.setItem(`${new Date()}`, sumUp2());
|
||||
taketheLastData(getCurrentDateFromDate(new Date()), sumUp2());
|
||||
resultContainer.appendChild(caloriesRecord);
|
||||
|
||||
//calValueText.innerText = `${goalvalue - sumUp2()}cal`;
|
||||
|
||||
// var back = document.getElementById("back");
|
||||
// back.addEventListener("click", function clickFn() {
|
||||
// foodResultText.style.display = "block";
|
||||
// foodResultText.style.backgroundColor = "#5cf089";
|
||||
// caloriesRecord.style.display = "none";
|
||||
// });
|
||||
});
|
||||
} catch (err) {
|
||||
console.log("ERR:", err);
|
||||
}
|
||||
}
|
||||
|
||||
let allFoodRecord = [];
|
||||
|
||||
function foodIntakeRecording(foodName, calories) {
|
||||
let food = {};
|
||||
food["Name"] = foodName;
|
||||
food["Calories"] = calories;
|
||||
allFoodRecord.push(food);
|
||||
localStorage.setItem("dataBag", JSON.stringify(allFoodRecord));
|
||||
genTable();
|
||||
}
|
||||
|
||||
function sumUp() {
|
||||
const totalCalories = allFoodRecord.reduce(
|
||||
(accumulator, currentValue) => accumulator + currentValue.Calories,
|
||||
0
|
||||
);
|
||||
|
||||
const totalCal = document.createElement("div");
|
||||
totalCal.className = "totalcal";
|
||||
totalCal.innerHTML = `<div>Total Calories: ${totalCalories}</div>`;
|
||||
caloriesRecord.appendChild(totalCal);
|
||||
}
|
||||
|
||||
function sumUp2() {
|
||||
const totalCalories = allFoodRecord.reduce(
|
||||
(accumulator, currentValue) => accumulator + currentValue.Calories,
|
||||
0
|
||||
);
|
||||
|
||||
return totalCalories;
|
||||
}
|
||||
|
||||
function genTable() {
|
||||
//caloriesRecord.innerHTML = "";
|
||||
|
||||
for (let i = 0; i < allFoodRecord.length; i++) {
|
||||
const foodItem = document.createElement("div");
|
||||
foodItem.className = "fooditem";
|
||||
foodItem.innerHTML = `
|
||||
<div>${allFoodRecord[i].Name}${allFoodRecord[i].Calories}</div>
|
||||
`;
|
||||
caloriesRecord.appendChild(foodItem);
|
||||
}
|
||||
}
|
||||
|
||||
let wholeDayRecord = [];
|
||||
|
||||
function taketheLastData(x, y) {
|
||||
let dailydata = {};
|
||||
dailydata["date"] = x;
|
||||
dailydata["totalCalories"] = y;
|
||||
wholeDayRecord.push(dailydata);
|
||||
localStorage.setItem(
|
||||
"dataBag",
|
||||
JSON.stringify(wholeDayRecord[wholeDayRecord.length - 1])
|
||||
);
|
||||
genBar();
|
||||
}
|
||||
|
||||
function genBar() {
|
||||
for (let i = 0; i < wholeDayRecord.length; i++) {
|
||||
const barcontainer = document.createElement("div");
|
||||
barcontainer.className = "barcontainer";
|
||||
|
||||
const barHeight = generateBarHeight(
|
||||
wholeDayRecord[wholeDayRecord.length - 1].totalCalories
|
||||
);
|
||||
|
||||
barcontainer.innerHTML = `
|
||||
<div class="bar" style="height: ${barHeight}%"></div>
|
||||
<div class="day">${wholeDayRecord[wholeDayRecord.length - 1].date}</div>
|
||||
<div class="totalcalnum">${
|
||||
wholeDayRecord[wholeDayRecord.length - 1].totalCalories
|
||||
}</div>
|
||||
`;
|
||||
|
||||
barChartContainer.appendChild(barcontainer);
|
||||
}
|
||||
}
|
||||
|
||||
//date
|
||||
const dateContainer = document.getElementById("dateContainer");
|
||||
const prevButton = document.getElementById("prevButton");
|
||||
const nextButton = document.getElementById("nextButton");
|
||||
const currentDateElement = document.getElementById("currentDate");
|
||||
|
||||
function generateBarHeight(totalCalories) {
|
||||
// 在这里根据总热量数据计算柱状图的高度百分比
|
||||
// 您可以根据实际需求来定义计算逻辑
|
||||
// 这里简单地将总热量数据除以一个固定值来获取百分比
|
||||
const maxHeight = 100; // 最大高度百分比
|
||||
const maxValue = 3000; // 最大的总热量值
|
||||
const barHeight = (totalCalories / maxValue) * maxHeight;
|
||||
console.log();
|
||||
return barHeight;
|
||||
}
|
||||
|
||||
// 调用生成柱状图的函数
|
||||
genBar();
|
||||
|
||||
// function generateBarHeight() {
|
||||
// var max = 3500;
|
||||
// var percentage = (sumUp2 / max) * 100;
|
||||
// return percentage;
|
||||
// }
|
||||
|
||||
// document.getElementById("bar1").style.height = generateBarHeight() + "%";
|
||||
// document.getElementById("bar2").style.height = generateBarHeight() + "%";
|
||||
// document.getElementById("bar3").style.height = generateBarHeight() + "%";
|
||||
// document.getElementById("bar4").style.height = generateBarHeight() + "%";
|
||||
// document.getElementById("bar5").style.height = generateBarHeight() + "%";
|
||||
// document.getElementById("bar6").style.height = generateBarHeight() + "%";
|
||||
// document.getElementById("bar7").style.height = generateBarHeight() + "%";
|
||||
|
||||
// var currentDate = new Date();
|
||||
// document.getElementById("day1").innerHTML = currentDate.getDate() - 6;
|
||||
// document.getElementById("day2").innerHTML = currentDate.getDate() - 5;
|
||||
// document.getElementById("day3").innerHTML = currentDate.getDate() - 4;
|
||||
// document.getElementById("day4").innerHTML = currentDate.getDate() - 3;
|
||||
// document.getElementById("day5").innerHTML = currentDate.getDate() - 2;
|
||||
// document.getElementById("day6").innerHTML = currentDate.getDate() - 1;
|
||||
// document.getElementById("day7").innerHTML = currentDate.getDate();
|
||||
|
||||
function getCurrentDateFromMounthandYear(date) {
|
||||
const year = date.getFullYear();
|
||||
const month = new Intl.DateTimeFormat("en-US", {
|
||||
month: "short",
|
||||
}).format(date);
|
||||
const day = String(date.getDate()).padStart(2, "0");
|
||||
return `${month}${year}`;
|
||||
}
|
||||
|
||||
function getCurrentDateFromDate(date) {
|
||||
const year = date.getFullYear();
|
||||
const month = new Intl.DateTimeFormat("en-US", {
|
||||
month: "short",
|
||||
}).format(date);
|
||||
const day = String(date.getDate()).padStart(2, "0");
|
||||
return `${day}`;
|
||||
}
|
||||
|
||||
function updateDate() {
|
||||
const currentDate = new Date();
|
||||
currentDateElement.textContent =
|
||||
getCurrentDateFromMounthandYear(currentDate);
|
||||
updateWeekChart(currentDate);
|
||||
}
|
||||
|
||||
function goToPreviousDay() {
|
||||
const currentDate = new Date(currentDateElement.textContent);
|
||||
currentDate.setDate(currentDate.getDate() - 1);
|
||||
currentDateElement.textContent = getCurrentDateFromDate(currentDate);
|
||||
updateWeekChart(currentDate);
|
||||
}
|
||||
|
||||
function goToNextDay() {
|
||||
const currentDate = new Date(currentDateElement.textContent);
|
||||
currentDate.setDate(currentDate.getDate() + 1);
|
||||
currentDateElement.textContent = getCurrentDateFromDate(currentDate);
|
||||
updateWeekChart(currentDate);
|
||||
}
|
||||
|
||||
prevButton.addEventListener("click", goToPreviousDay);
|
||||
nextButton.addEventListener("click", goToNextDay);
|
||||
|
||||
updateDate();
|
||||
});
|
Reference in New Issue
Block a user