-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
80 lines (69 loc) · 2.25 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const container= document.querySelector(".container");
const optionsContainer=document.querySelector(".options-container");
const country="in";
const options=["general","entertainment","health","science","sports","technology",];
// N number of requests per day here, 100
let requestURL;
// create cards from data
const generateUI=(articles)=>{
for(let item of articles){
let card=document.createElement("div");
card.classList.add("news-card");
card.innerHTML=
`
<div class="news-image-container">
<img src="${item.urlToImage||"./newspaper.jpg"}" alt=""/>
</div>
<div class="news-content">
<div class="news-title">
${item.title}
</div>
<div class="news-description">
${item.description||item.content||""}
</div>
<a href="${item.url}" target="_blank" class="view-button">Read More</a>
</div>
`;
container.appendChild(card);
}
};
// NEWS API CALL
const getNews = async () => {
container.innerHTML="";
let response=await fetch(requestURL);
if(!response.ok){
alert("Data unavailable at the moment. Please try again later..!");
return false;
}
let data=await response.json();
generateUI(data.articles);
};
// CATEGORY SELECTION
const selectCategory=(e,category)=>{
let options=document.querySelectorAll(".option");
options.forEach((element)=>{
element.classList.remove("active");
});
requestURL=`https://newsapi.org/v2/top-headlines?country=${country}&category=${category}&apiKey=${apiKey}`;
e.target.classList.add("active");
getNews();
};
// OPTIONS BUTTONS
const createOptions=()=>{
for(let i of options){
optionsContainer.innerHTML+=`
<button class="option ${
i=="general"? "active" :""
}" onclick="selectCategory(event,'${i}')">${i}</button>
`;
}
};
const init=()=>{
optionsContainer.innerHTML="";
getNews();
createOptions();
};
window.onload=()=>{
requestURL=`https://newsapi.org/v2/top-headlines?country=${country}&category=general&apiKey=${apiKey}`;
init();
};