-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
48 lines (40 loc) · 1.48 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
// Function to fetch the NASA image of the day data
async function fetchAPOD() {
const apiKey = "BnjlgCuASb6JOgvfmmMWhtw5TN9eiRyuD8sCTxJa";
const apiUrl = `https://api.nasa.gov/planetary/apod?api_key=${apiKey}`;
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error("Failed to fetch data from NASA API");
}
const data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
// Function to format the date to a more readable format (e.g., July 21, 2023)
function formatDate(date) {
const options = { year: "numeric", month: "long", day: "numeric" };
return date.toLocaleDateString("en-US", options);
}
// Function to display the NASA image of the day data
function displayAPOD(data) {
const apodImage = document.getElementById("apodImage");
const apodTitle = document.getElementById("apodTitle");
const apodDate = document.getElementById("apodDate");
const apodExplanation = document.getElementById("apodExplanation");
apodImage.src = data.url;
apodImage.alt = data.title;
apodTitle.textContent = data.title;
const date = new Date();
const formattedDate = formatDate(date);
apodDate.textContent = formattedDate;
apodExplanation.textContent = data.explanation;
}
// Call the function to fetch the data and display it on the page
fetchAPOD().then((data) => {
if (data) {
displayAPOD(data);
}
});