-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.js
67 lines (57 loc) · 2.2 KB
/
web.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
const API_KEY = "d39b106301994a42adb2e5a593aff527";
const url = "https://newsapi.org/v2/everything?q=";
window.addEventListener("load", () => fetchNews("India"));
function reload() {
window.location.reload();
}
async function fetchNews(query) {
const res = await fetch(`${url}${query}&apiKey=${ API_KEY }`);
const data = await res.json();
console.log(data);
bindData(data.articles);
}
function bindData(articles) {
const cardsContainer = document.getElementById("cards-container");
const newsCardTemplate = document.getElementById("template-news-card");
cardsContainer.innerHTML = "";
articles.forEach(articles => {
if (!articles.urlToImage) return;
const cardColne = newsCardTemplate.content.cloneNode(true);// every div in card contaner get clone for this we use
// above clon node funtion
fillDataInCard(cardColne, articles);
cardsContainer.appendChild(cardColne);
});
}
function fillDataInCard(cardColne, article) {
const newsImg = cardColne.querySelector('#news-img');
const newsTitle = cardColne.querySelector('#news-title');
const newsSource = cardColne.querySelector('#news-source');
const newsDes = cardColne.querySelector('#news-des');
newsImg.src = article.urlToImage;
newsTitle.innerHTML = article.title;
newsDes.innerHTML = article.description;
const date = new Date(article.publisheAt).toLocaleDateString("en_us", {
timeZone: "Asia"
});// it is a JS lab which help to convert date into readable from
newsSource.innerHTML = `${article.source.name} :${date} `;
cardColne.firstElementChild.addEventListener("click", () => {
window.open(article.url, "_blank");
});
}
let curSelectedNav = null;
function onNavItemClick(id) {
fetchNews(id);
const navItem = document.getElementById(id);// to see which nav item is active
curSelectedNav?.classList.remove('active');
curSelectedNav = navItem;
curSelectedNav.classList.add('active');
}
const searchButton = document.getElementById("search-button");
const searchText = document.getElementById("search-text");
searchButton.addEventListener("click", () => {
const query = searchText.value;
if (!query) return;
fetchNews(query);
curSelectedNav.classList.remove('active');
curSelectedNav = null;
})