-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
47 lines (40 loc) · 1.87 KB
/
index.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
console.log("This is my index js file");
// Initialize the news api parameters
let source = 'bbc-news';
let apiKey = 'b2a7549603c346cc86f0c8c918d9a65c'
// Grab the news container
let newsAccordion = document.getElementById('newsAccordion');
// Create an ajax get request
const xhr = new XMLHttpRequest();
xhr.open('GET', `https://newsapi.org/v2/top-headlines?sources=${source}&apiKey=${apiKey}`, true);
// What to do when response is ready
xhr.onload = function () {
if (this.status === 200) {
let json = JSON.parse(this.responseText);
let articles = json.articles;
console.log(articles);
let newsHtml = "";
articles.forEach(function(element, index) {
// console.log(element, index)
let news = `<div class="card">
<div class="card-header" id="heading${index}">
<h2 class="mb-0">
<button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapse${index}"
aria-expanded="false" aria-controls="collapse${index}">
<b>Breaking News ${index+1}:</b> ${element["title"]}
</button>
</h2>
</div>
<div id="collapse${index}" class="collapse" aria-labelledby="heading${index}" data-parent="#newsAccordion">
<div class="card-body"> ${element["content"]}. <a href="${element['url']}" target="_blank" >Read more here</a> </div>
</div>
</div>`;
newsHtml += news;
});
newsAccordion.innerHTML = newsHtml;
}
else {
console.log("Some error occured")
}
}
xhr.send()