-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
57 lines (50 loc) · 1.78 KB
/
script.js
File metadata and controls
57 lines (50 loc) · 1.78 KB
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
const apiUrl = 'news.json';
const newsContainer = document.getElementById('news-container');
let articles = [];
async function fetchNews() {
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log("Fetched articles:", data.articles);
articles = shuffleArray(data.articles);
renderNews();
} catch (error) {
console.error('Error fetching news:', error);
newsContainer.innerHTML = '<p>Error fetching articles.</p>';
}
}
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
function renderNews() {
newsContainer.innerHTML = '';
if (articles.length > 0) {
const randomIndex = Math.floor(Math.random() * articles.length);
const article = articles[randomIndex];
const articleElement = document.createElement('div');
articleElement.className = 'news-article';
articleElement.innerHTML = `
<h2>${article.title}</h2>
<p>${article.description}</p>
<img src="${article.urlToImage}" alt="${article.title}">
`;
articleElement.addEventListener('click', () => {
window.open(article.url, '_blank');
});
newsContainer.appendChild(articleElement);
} else {
newsContainer.innerHTML = '<p>No articles available.</p>';
}
}
function refreshNews() {
renderNews();
}
document.getElementById('refresh-button').addEventListener('click', refreshNews);
fetchNews();