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
|
const appOutput = document.querySelector('#app'); const apiKey = 'T6l8P8ICK6XZr1u3OeA0qoGUFrEcSM5R'; const sections = ['Technology', 'Science', 'Magazine']; const articleNum = 3;
const render = function (articles, section) { appOutput.innerHTML += '<h3 class="category">' + section + ':' + '</h3>' + articles.map(function (article) { return (` <div class="container"> <ul class="title"> <li>${sanitizeHTML(article.url)}</li> <a class="link" href="${sanitizeHTML(article.url)}" target="_blank">Read more</a> </ul> </div> <br> `); }).join('') };
const getLastNStories = function (articles) { return articles.slice(0, articleNum) }
const getStories = function (section) { fetch(`https://api.nytimes.com/svc/topstories/v2/${section}.json?api-key=${apiKey}`).then( function (response) { if (response.ok) { return response.json(); } else { return Promise.reject(response); }; }).then(function (data) { const lastNStories = getLastNStories(data.results); render(lastNStories, section); }).catch(response => { console.log("something went wrong", response); appOutput.textContent = "Something went wrong..."; }); };
sections.forEach(function (section) { getStories(section); });
|