forked from marcushellberg/alternative-news
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
50 lines (44 loc) · 1.61 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
const apiKey = '6f4fa5447bb24a2687edecc4c1df43b4';
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>
`;
}