Today's NASA APOD
Using NASA APOD API to get today's APOD media.
by liderrick
HTML
<h2>Today's NASA Astronomy Picture of the Day (APOD)</h2>
<figure id="todayAPOD">
<div id="todayPhotoDiv"></div>
<figcaption id="todayCaption1"></figcaption>
<figcaption id="todayCaption2"></figcaption>
<figcaption id="todayCaption3"></figcaption>
<figcaption id="todayCaption4"></figcaption>
</figure>
CSS
img {
width: auto;
max-width: 100%;
height: auto;
max-height: 100%;
align-content: center;
}
figure {
padding: 10px;
text-align: center;
}
figcaption {
text-align: left;
}
.title {
font-style: bold;
}
#todayAPOD {
border: solid lightgrey;
}
iframe {
width: 960px;
height: 540px;
border: 0;
}
#resolutionLabel {
margin-left: 30px;
}
#stdRadio {
margin-left: 15px;
}
#submitDate {
margin-left: 50px;
}
JavaScript
var apiKey = "Q04R5uu3AmDLtMki1TxSp3QhLzIAbSH2qnmf7rT7";
function getTodayAPOD() {
var req = new XMLHttpRequest();
req.open("GET", "https://api.nasa.gov/planetary/apod?api_key=" + apiKey, true);
req.addEventListener("load", function() {
if(req.status >= 200 && req.status < 400)
{
var response = JSON.parse(req.responseText);
/* Clears text content of captions */
document.getElementById("todayCaption1").textContent = "";
document.getElementById("todayCaption2").textContent = "";
document.getElementById("todayCaption3").textContent = "";
document.getElementById("todayCaption4").textContent = "";
/* Clears img or iframe from todayPhotoDiv */
var todayPhotoDivNode = document.getElementById("todayPhotoDiv");
while(todayPhotoDivNode.hasChildNodes() == true)
{
todayPhotoDivNode.removeChild(todayPhotoDivNode.lastChild);
}
if(response.media_type == "image")
{
var img = document.createElement("img");
img.id = "todayPhoto";
document.getElementById("todayPhotoDiv").appendChild(img);
if(response.hasOwnProperty("hdurl"))
{
document.getElementById("todayPhoto").src = response.hdurl;
}
else
{
document.getElementById("todayPhoto").src = response.url;
}
}
else if(response.media_type == "video")
{
var vid = document.createElement("iframe");
vid.id = "todayVideo";
document.getElementById("todayPhotoDiv").appendChild(vid);
document.getElementById("todayVideo").src = response.url;
}
document.getElementById("todayCaption1").textContent = "Title: " + response.title;
document.getElementById("todayCaption2").textContent = "Date: " + response.date;
document.getElementById("todayCaption3").textContent = "Explanation: " + response.explanation;
if(response.hasOwnProperty("copyright"))
{
document.getElementById("todayCaption4").textContent = "Copyright: " + response.copyright;
}
}
else
{
console.log("Error in network request: " +...