-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
95 lines (71 loc) · 2.47 KB
/
app.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
// Using query
// async function fetchArticle(title) {
// const response = await fetch(`https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=${title}&origin=*`);
// const data = await response.json();
// console.log(data.parse.text["*"]);
// return data;
// }
// console.log(fetchArticle("Book"));
// Using parse
async function fetchArticle(pageTitle) {
const url = "https://en.wikipedia.org/w/api.php?" +
new URLSearchParams({
origin: "*", // Required to avoid CORS issues
action: "parse", // 'parse' returns the HTML content of the page
page: pageTitle, // The Wikipedia page title
format: "json" // Get data in JSON format
});
try {
const response = await fetch(url);
const data = await response.json();
const htmlData = data.parse.text["*"]
// Page title
const title = createElement("h1")
title.innerText = pageTitle
// Save on Local storage
const pageData = {
title: pageTitle,
content: htmlData
};
localStorage.setItem(pageTitle, JSON.stringify(pageData));
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchArticle("Book")
fetchArticle("Pet door");
fetchArticle("Wikipedia");
// Helper functions
const createElement = (elt) => document.createElement(elt)
// Retrieving JSON data
const aside = document.querySelector("aside")
/**
* Improve the loop w/ object.key
* https://javascript.info/localstorage
*/
for (let i = 0; i < localStorage.length; i++) {
let key = localStorage.key(i);
const savedData = JSON.parse(localStorage.getItem(key));
const title = createElement("h1")
title.innerText = savedData.title
aside.appendChild(title)
}
function displayPage(event) {
const output = event.currentTarget
const main = document.querySelector("main")
const title = createElement("h1")
const content = createElement("div")
title.innerText = output.innerText
const titleTxt = title.innerText
const article = JSON.parse(localStorage.getItem(titleTxt))
content.innerHTML = article.content
// Clear the content first
main.innerHTML = ""
main.appendChild(title)
main.appendChild(content)
}
// Handle click on title
const titleList = document.querySelectorAll("h1")
for (let i = 0; i < titleList.length; i++) {
titleList[i].addEventListener("click", displayPage);
}