-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
89 lines (74 loc) · 2.81 KB
/
Copy pathscript.js
File metadata and controls
89 lines (74 loc) · 2.81 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const apiKey = 'ICNqRASZWMtwap7Tipdd8D71ByJaBJxMKJXkANyE';
// 1. Fetch APOD (Now accepts an optional date parameter)
async function fetchAPOD(date = '') {
const title = document.getElementById('apod-title');
const explanation = document.getElementById('apod-explanation');
const mediaWrapper = document.getElementById('media-wrapper');
const dateDisplay = document.getElementById('apod-date');
// Show loading state
title.innerText = "Loading...";
mediaWrapper.innerHTML = '';
explanation.innerText = '';
// Build URL: If date is provided, add &date=YYYY-MM-DD
let url = `https://api.nasa.gov/planetary/apod?api_key=${apiKey}`;
if (date) {
url += `&date=${date}`;
}
try {
const response = await fetch(url);
const data = await response.json();
// Check for error (e.g., future date)
if (data.code === 400) {
title.innerText = "Error: " + data.msg;
return;
}
title.innerText = data.title;
dateDisplay.innerText = data.date;
explanation.innerText = data.explanation;
if (data.media_type === 'image') {
const img = document.createElement('img');
img.src = data.url;
img.alt = data.title;
mediaWrapper.appendChild(img);
} else if (data.media_type === 'video') {
const iframe = document.createElement('iframe');
iframe.src = data.url;
iframe.width = "100%";
iframe.height = "400";
iframe.frameBorder = "0";
mediaWrapper.appendChild(iframe);
}
} catch (error) {
console.log(error);
title.innerText = "Failed to load data.";
}
}
// 2. Button Click Handler
function fetchAPODByDate() {
const dateInput = document.getElementById('date-picker').value;
if (dateInput) {
fetchAPOD(dateInput);
} else {
alert("Please select a date first!");
}
}
// 3. Setup Date Picker Max Date (Prevent future dates)
const today = new Date().toISOString().split('T')[0];
document.getElementById('date-picker').max = today;
// 4. Random Date Generator
function fetchRandomAPOD() {
// NASA APOD started on June 16, 1995
const startDate = new Date('1995-06-16').getTime();
const today = new Date().getTime();
// Generate a random time between start and today
const randomTime = startDate + Math.random() * (today - startDate);
// Convert timestamp back to YYYY-MM-DD format
const randomDate = new Date(randomTime);
const dateString = randomDate.toISOString().split('T')[0];
// Update the date picker input so the user sees which date was picked
document.getElementById('date-picker').value = dateString;
// Fetch the data
fetchAPOD(dateString);
}
// Initial Load (Loads today's picture)
fetchAPOD();