-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
341 lines (309 loc) · 12.3 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Assignments
const baseURL = "http://localhost:3000/recipes";
const navBar = document.getElementById("navigation");
const selectBar = document.getElementById("select");
const btnAddRec = document.getElementById("add-recipe");
const mealSelector = document.getElementById("meal-selector");
const btnLoadSel = document.getElementById("meal-select");
const recListSec = document.getElementById("recipe-list");
const recDispSec = document.getElementById("recipe-display");
const recipeForm = document.getElementById("add-recipe-form");
const btnAddIng = document.getElementById("btn-add-ingredient");
const btnAddInstr = document.getElementById("btn-add-instructions");
const btnSubmitRec = document.getElementById("submit-new-recipe");
const btnResetForm = document.getElementById("add-form-reset")
// DOMContentLoaded
document.addEventListener("DOMContentLoaded", () => {
fetchRecipes()
})
// Fetches
function fetchRecipes() {
return fetch(baseURL)
.then(resp => resp.json())
.then(renderAllRecipes)
console.log("Hello world")
}
function getRecipeDetails(e) {
return fetch(baseURL + `/${e.target.id}`)
.then(resp => resp.json())
.then(renderDetails)
}
function patchComment(e) {
// Look up recipe ID and retrieve the value from the comment box
const id = e.target.parentNode.parentNode.id;
const newCommentInput = document.getElementById("new-comment")
const newComment = newCommentInput.value;
// Patch to the recipe through the ID, push new comment to the comment array and render
fetch(baseURL + `/${id}`)
.then(resp => resp.json())
.then(recObj => {
let comments = recObj.comments;
comments.push(`${newComment}`)
fetch(baseURL + `/${id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify({comments})
}) .then(renderComment(newComment))
})
}
function postNewRecipe(newRecObj) {
// console.log(JSON.stringify(newRecObj))
fetch(baseURL, {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(newRecObj)
})
.then(resp => resp.json())
.catch(error => console.error('Error', error))
.then(reloadPage)
}
// Rendering
function renderAllRecipes(recArr) {
// This hides the recipe display if one was being displayed
recDispSec.innerHTML = "";
recArr.forEach(renderOneRecipe)
}
function renderOneRecipe(recipe) {
const recList = document.createElement("li")
recList.id = recipe.id;
recList.className = recipe.mealtype;
recList.innerText = recipe.name;
recList.addEventListener("click", getRecipeDetails)
recListSec.appendChild(recList)
}
function renderDetails(recipe) {
// Hide the recipe index list when rendering details of a recipe
recListSec.style="display: none";
btnAddRec.className = "hide";
// Create the recipe card
const recCard = document.createElement("div");
recCard.className = "card";
recCard.id = recipe.id;
// Rendering the recipe image, name and author
recCard.innerHTML = `
<img class="center" src="${recipe.img}">
<h2 align="middle">${recipe.name}</h2>
<h3 align="middle">By ${recipe.author}</h3>
`;
// Check to see if there is a source link, adding link if available
if(recipe.source.length > 0) {
const recipeLink = document.createElement("a");
recipeLink.style.marginLeft = "auto";
recipeLink.style.marginRight = "auto";
recipeLink.innerHTML = `
<a target="_blank" href="${recipe.source}">Recipe source link</a>
`;
recCard.append(recipeLink)
}
//Creating ingredient header and list using a forEach
const ingredientHeader = document.createElement("h3");
ingredientHeader.innerText = "Ingredients:";
const recIngList = document.createElement("ul");
recIngList.id = "ingList";
let ingArr = recipe.ingredients;
ingArr.forEach(ing => {
const ingLi = document.createElement("li");
ingLi.innerText = `${ing}`;
recIngList.append(ingLi)
})
//Creating instruction header and list using a forEach
const instrHeader = document.createElement("h3");
instrHeader.innerText = "Instructions:";
const recInstructions = document.createElement('ol');
recInstructions.className = "card";
let instrArr = recipe.instructions;
instrArr.forEach(instr => {
const instrLi = document.createElement("li");
instrLi.innerText = `${instr}`;
recInstructions.append(instrLi)
})
// Create a comment section and submit button
const commentHeader = document.createElement("h3");
commentHeader.innerText = "Comments:";
const btnAddComment = document.createElement("button");
btnAddComment.id = "btn-add-comment";
btnAddComment.innerText = " Add a comment ";
btnAddComment.addEventListener("click", addCommentForm);
const commentSection = document.createElement("ul");
commentSection.className = "card";
commentSection.id = "comment-section";
let commArr = recipe.comments;
if (commArr.length > 0) {
commArr.forEach(comment => {
const commentPara = document.createElement("li");
commentPara.innerText = `${comment}`;
commentSection.append(commentPara)
})};
// Create the back button, back button clone for the top of the page and add event listener
const backBtn = document.createElement("button");
backBtn.id = "back-btn";
backBtn.innerText = " Back to Index ";
backBtn.addEventListener("click", revealList);
const backBtnClone = backBtn.cloneNode(true);
backBtnClone.id = "back-btn-clone";
backBtnClone.addEventListener("click", revealList);
recCard.append(ingredientHeader, recIngList, instrHeader, recInstructions, commentHeader, btnAddComment, commentSection, backBtn);
recDispSec.appendChild(recCard);
selectBar.classList = "hide";
navBar.append(backBtnClone)
}
function renderComment() {
// Hide the add comment button so you can't add more than one at a time
const btnAddComment = document.getElementById("btn-add-comment");
btnAddComment.style="display: in-block";
// Look up the comment section
const commentSection = document.getElementById("comment-section");
const newCommentLi = document.createElement("li");
// Create a new comment element and insert text from form, append to comments
let newCommentInput = document.getElementById("new-comment");
newCommentLi.innerText = newCommentInput.value;
commentSection.append(newCommentLi);
// Remove the form and button after submitting the comment
const commentForm = document.getElementById("comment-form");
commentForm.remove();
const btnCommSubmit = document.getElementById("btn-comm-submit");
btnCommSubmit.remove();
}
// Event listeners
btnAddRec.addEventListener("click", toggleFormVisibility)
// btnLoadSel.addEventListener("click", filterRecipesByMeal)
btnAddIng.addEventListener("click", addIngBox)
btnAddInstr.addEventListener("click", addInstrBox)
// recipeForm.addEventListener("submit", createNewRecObj)
btnSubmitRec.addEventListener("click", createNewRecObj)
btnResetForm.addEventListener("click", resetForm)
// Event Handlers
function revealList() {
recDispSec.innerHTML = "";
recListSec.style="display: inline-block";
document.getElementById("back-btn-clone").remove();
btnAddRec.classList.remove("hide");
selectBar.classList.remove("hide")
}
function addCommentForm() {
// Find the comment section and the add comment button so we can hide it later
const commentSection = document.getElementById("comment-section");
const btnAddComment = document.getElementById("btn-add-comment");
btnAddComment.style="display: none";
// Add the comment form to the comment section
const commentForm = document.createElement("form");
commentForm.id = "comment-form";
commentForm.innerHTML = `
<textarea required id="new-comment" placeholder="Add your comment for this recipe"></textarea>
`
const btnCommSubmit = document.createElement("button");
btnCommSubmit.innerText = " Submit Comment ";
btnCommSubmit.id = "btn-comm-submit";
btnCommSubmit.addEventListener("click", patchComment);
commentSection.prepend(commentForm, btnCommSubmit);
}
function toggleFormVisibility(e) {
recListSec.style="display: none";
selectBar.className = "hide";
if (e.target.innerText === "Add A Recipe") {
e.target.innerText = "Hide Form";
document.getElementById("add-recipe-div").classList.remove("hide")
} else if (e.target.innerText !== "Add A Recipe") {
e.target.innerText = "Add A Recipe";
document.getElementById("add-recipe-div").classList.add("hide");
recListSec.style="display:inline-block";
selectBar.classList.remove("hide")
}
}
function filterRecipesByMeal() {
// e.preventDefault()
const recipeList = document.getElementById("recipe-list");
const mealType = mealSelector.value;
let listLi = recipeList.getElementsByTagName("li")
// console.log(listLi)
for(i=0; i < listLi.length; i++) {
if (mealType === "Show All"){
listLi[i].style.display = ""
} else if (listLi[i].className === mealType) {
listLi[i].style.display = ""
} else {
listLi[i].style.display = "none"
}
}
}
function addIngBox(e) {
const lineBreak = document.createElement("br");
const newIngBox = document.createElement("input");
newIngBox.type = "text";
newIngBox.className = "add-ingredient"
newIngBox.name = "add-ingredient";
const addButton = e.target.parentNode; // targets the div
addButton.insertBefore(newIngBox, e.target);
addButton.insertBefore(lineBreak, e.target)
}
function addInstrBox(e) {
const lineBreak = document.createElement("br");
const newInstrBox = document.createElement("input");
newInstrBox.type = "text";
newInstrBox.className = "add-instructions";
newInstrBox.name = "add-instructions";
const addButton = e.target.parentNode; // targets the div
addButton.insertBefore(newInstrBox, e.target);
addButton.insertBefore(lineBreak, e.target)
}
function createNewRecObj (e) {
e.preventDefault();// Prevent default on a submit is preventing you from the automatic POST, which in turn stops the page from refreshing
//Create our Ingredients array from the HTML collection pulled from our form
let ingArr = [];
let ingColl = document.getElementsByClassName("add-ingredient");
for (let i = 0; i < ingColl.length; i++) {
if (ingColl[i].value.length > 0) {
ingArr.push(ingColl[i].value)
}
};
// Create our Instructions array from the HTML collection pulled from our form
let instrArr = [];
let instrColl = document.getElementsByClassName("add-instructions");
for (let i = 0; i < instrColl.length; i++) {
if (instrColl[i].value.length > 0) {
instrArr.push(instrColl[i].value)
}
};
// Create initial comment array
let commArr = [];
if (document.getElementById("init-comm").value.length > 0) {
commArr.push(document.getElementById("init-comm").value)
};
//Create our new Recipe Object to be POST-ed to the database
let newRecObj = {
img: document.getElementById("add-img").value,
video: document.getElementById("add-video").value,
name: document.getElementById("add-name").value,
source: document.getElementById("add-source").value,
author: document.getElementById("add-author").value,
mealtype: document.getElementById("add-meal-selector").value,
preptime: document.getElementById("add-preptime").value,
cooktime: document.getElementById("add-cooktime").value,
servings: document.getElementById("add-servings").value,
instructions: instrArr,
ingredients: ingArr,
comments: commArr
}
// console.log(newRecObj)
postNewRecipe(newRecObj);
}
// This is for a future version
// function createNewRecObj (e) {
// e.preventDefault();
// let newRecObj = {};
// console.log(newRecObj)
// }
function reloadPage() {
location.reload(true);
}
function submitForm() {
recipeForm.submit()
}
function resetForm() {
recipeForm.reset()
}