Javascript Exit Ticket
Here I am just using the Newscatcher API to generate 4 news articles recently off of keywords in the search bar.
%%html
<head>
</head>
<body>
<form class="search" action="">
<input class="input" type="text" id="search-input" />
<input type="submit" value="Search" />
</form>
<table id="news-table">
<tr>
<th>Title</th>
<th>Link</th>
</tr>
</table>
<script>
const apiKey = 'wBn2KgxIdqAZCxawJSL8sWJTShXlc5lU70mmCN5mmqI';
const url = 'https://api.newscatcherapi.com/v2/search?q=';
const form = document.querySelector('.search');
const searchInput = document.getElementById('search-input');
const newsTable = document.getElementById('news-table');
form.addEventListener('submit', e => {
e.preventDefault();
const searchQuery = searchInput.value.trim();
if (searchQuery) {
const searchUrl = url + encodeURIComponent(searchQuery) + '&countries=US';
fetch(searchUrl, {
headers: {
'X-Api-Key': apiKey
}
})
.then(response => response.json())
.then(data => {
newsTable.innerHTML = '';
if (data.total_hits === 0) {
const noResultsRow = document.createElement('tr');
const noResultsMessage = document.createElement('td');
noResultsMessage.textContent = 'No results found.';
noResultsRow.appendChild(noResultsMessage);
newsTable.appendChild(noResultsRow);
} else {
//I only want four articles so it won't be cluttered
const results = data.articles.slice(0, 4);
results.forEach(article => {
const title = article.title;
const link = article.link;
const row = document.createElement('tr');
const titleCell = document.createElement('td');
const linkCell = document.createElement('td');
const linkElement = document.createElement('a');
linkElement.href = link;
linkElement.textContent = title;
titleCell.appendChild(linkElement);
row.appendChild(titleCell);
row.appendChild(linkCell);
newsTable.appendChild(row);
});
}
})
.catch(error => {
console.error('Error:', error);
});
}
});
</script>
</body>