-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
84 lines (72 loc) · 2.81 KB
/
Copy pathscript.js
File metadata and controls
84 lines (72 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
const apiKey ="hgoKL4SkS9PncsU3EQooBndYo011nMdL1QrxC85Y";
const searchForm = document.getElementById("search-form");
const imageContainer = document.getElementById("current-image-container");
const searchHistoryList = document.getElementById("search-history");
const currentDate = new Date().toISOString().split("T")[0];
const minDate = "1995-06-16";
function getCurrentImageOfTheDay() {
fetch(`https://api.nasa.gov/planetary/apod?&date=${currentDate}&api_key=${apiKey}`)
.then(response => response.json())
.then((data) => {
console.log(data);
imageContainer.innerHTML = `
<h1>NASA Picture of the Day</h1>
${data.media_type === "image" ? `<img src=${data.hdurl}>` : ''}
${data.media_type === "video" ? `<iframe src=${data.url}></iframe>` : ''}
<h3>${data.title}</h3>
<p>${data.explanation}</p>`;
})
.catch(error => {
console.log(error);
});
}
getCurrentImageOfTheDay();
searchForm.addEventListener("submit", (e) => {
e.preventDefault();
let searchInput = document.getElementById("search-input").value;
getImageOfTheDay(searchInput);
saveSearch(searchInput);
addSearchToHistory();
});
function getImageOfTheDay(date) {
if (date < minDate || date > currentDate) {
alert(`Please enter a date between ${minDate}, and ${currentDate}.`);
return;
}
fetch(`https://api.nasa.gov/planetary/apod?&date=${date}&api_key=${apiKey}`)
.then(response => response.json())
.then((data) => {
console.log(data);
imageContainer.innerHTML = `
<h1>Picture on ${data.date}</h1>
${data.media_type === "image" ? `<img src=${data.hdurl}>` : ''}
${data.media_type === "video" ? `<iframe src=${data.url}></iframe>` : ''}
<h3>${data.title}</h3>
<p>${data.explanation}</p>`;
})
.catch(error => {
console.log(error);
});
}
function saveSearch(date) {
if (date > minDate && date < currentDate) {
let savedDates = JSON.parse(localStorage.getItem("savedDates")) || [];
savedDates.push(date);
localStorage.setItem("savedDates", JSON.stringify(savedDates));
}
}
function addSearchToHistory() {
let savedDates = JSON.parse(localStorage.getItem("savedDates")) || [];
let unorderList = document.createElement("ul");
savedDates.forEach((date) => {
let listItem = document.createElement("li");
listItem.textContent = date;
listItem.addEventListener("click", () => {
getImageOfTheDay(date);
});
unorderList.appendChild(listItem);
});
searchHistoryList.innerHTML = "";
searchHistoryList.appendChild(unorderList);
}
addSearchToHistory();