-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
56 lines (50 loc) · 1.63 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
const apikey = "74ece3427d724ef492169afed5a24881";
const defaultSource = "the-washington-post";
const sourceSelector = document.querySelector("#sources");
const newsArticles = document.querySelector("main");
if ("serviceWorker" in navigator) {
window.addEventListener("load", () =>
navigator.serviceWorker
.register("sw.js")
.then(registration => console.log("Service Worker registered"))
.catch(err => "SW registration failed")
);
}
window.addEventListener("load", e => {
sourceSelector.addEventListener("change", evt =>
updateNews(evt.target.value)
);
updateNewsSources().then(() => {
sourceSelector.value = defaultSource;
updateNews();
});
});
window.addEventListener("online", () => updateNews(sourceSelector.value));
async function updateNewsSources() {
const response = await fetch(
`https://newsapi.org/v2/sources?apiKey=${apikey}`
);
const json = await response.json();
sourceSelector.innerHTML = json.sources
.map(source => `<option value="${source.id}">${source.name}</option>`)
.join("\n");
}
async function updateNews(source = defaultSource) {
newsArticles.innerHTML = "";
const response = await fetch(
`https://newsapi.org/v2/top-headlines?sources=${source}&sortBy=top&apiKey=${apikey}`
);
const json = await response.json();
newsArticles.innerHTML = json.articles.map(createArticle).join("\n");
}
function createArticle(article) {
return `
<div class="article">
<a href="${article.url}">
<h2>${article.title}</h2>
<img src="${article.urlToImage}" alt="${article.title}">
<p>${article.description}</p>
</a>
</div>
`;
}