-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
45 lines (40 loc) · 1.4 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
const apiKey='b43c9c5fdda249a08b3d15f316c8d180';
const blogContainer = document.getElementById
("blog-container");
async function fetchRandomNews() {
try {
const apiUrl = 'https://newsapi.org/v2/top-headlines?country=us&pageSize=10&apiKey=${apiKey}';
const response = await fetch(apiUrl);
const data = await response.json();
return data.articles;
} catch(errror) {
console.error("Error fetching random news", error);
return[];
}
}
function displayBlogs(articles){
blogContainer.innerHTML = "";
articles.forEach((article) => {
const blogCard = document.createElement("div")
blogCard.classList.add("blog-card")
const img=document.createElement("img")
img.src = article.urlToImage
img.alt = article.title
const title = document.createElement("h2")
title.textContent = article.title
const description = document.createElement("p")
description.textContent = article.description ;
blogCard.appendChild(img);
blogCard.appendChild(title);
blogCard.appendChild(description);
blogContainer.appendChild(blogCard);
});
}
(async () => {
try {
const articles = await fetchRandomNews();
displayBlogs(articles);
} catch (error) {
console.error("Error fetching random news",error);
}
})();