-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
313 lines (278 loc) · 10.8 KB
/
script.js
File metadata and controls
313 lines (278 loc) · 10.8 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
class RandomAnimalsApp {
constructor() {
this.viewCount = 0;
this.favorites = JSON.parse(localStorage.getItem('animalFavorites') || '[]');
this.currentAnimal = null;
this.initializeElements();
this.bindEvents();
this.updateStats();
this.renderFavorites();
}
initializeElements() {
this.elements = {
fetchRandom: document.getElementById('fetchRandom'),
fetchDog: document.getElementById('fetchDog'),
fetchCat: document.getElementById('fetchCat'),
fetchFox: document.getElementById('fetchFox'),
loading: document.getElementById('loading'),
animalCard: document.getElementById('animalCard'),
animalImg: document.getElementById('animalImg'),
animalName: document.getElementById('animalName'),
animalDescription: document.getElementById('animalDescription'),
animalType: document.getElementById('animalType'),
animalSource: document.getElementById('animalSource'),
errorMessage: document.getElementById('errorMessage'),
viewCount: document.getElementById('viewCount'),
favoriteCount: document.getElementById('favoriteCount'),
favoritesList: document.getElementById('favoritesList')
};
}
bindEvents() {
this.elements.fetchRandom.addEventListener('click', () => this.fetchRandomAnimal());
this.elements.fetchDog.addEventListener('click', () => this.fetchSpecificAnimal('dog'));
this.elements.fetchCat.addEventListener('click', () => this.fetchSpecificAnimal('cat'));
this.elements.fetchFox.addEventListener('click', () => this.fetchSpecificAnimal('fox'));
// Add favorite functionality to animal name
this.elements.animalName.addEventListener('click', () => this.toggleFavorite());
}
async fetchRandomAnimal() {
const apis = [
() => this.fetchDogAPI(),
() => this.fetchCatAPI(),
() => this.fetchFoxAPI(),
() => this.fetchRandomDogAPI(),
() => this.fetchRandomCatAPI()
];
const randomAPI = apis[Math.floor(Math.random() * apis.length)];
await randomAPI();
}
async fetchSpecificAnimal(type) {
switch(type) {
case 'dog':
await this.fetchDogAPI();
break;
case 'cat':
await this.fetchCatAPI();
break;
case 'fox':
await this.fetchFoxAPI();
break;
}
}
async fetchDogAPI() {
try {
this.showLoading();
const response = await fetch('https://dog.ceo/api/breeds/image/random');
const data = await response.json();
if (data.status === 'success') {
const breed = this.extractBreedFromUrl(data.message);
this.displayAnimal({
image: data.message,
name: breed,
description: `A beautiful ${breed} dog`,
type: 'Dog',
source: 'Dog CEO API'
});
} else {
throw new Error('Failed to fetch dog');
}
} catch (error) {
this.showError('Failed to fetch dog image');
}
}
async fetchCatAPI() {
try {
this.showLoading();
const response = await fetch('https://api.thecatapi.com/v1/images/search');
const data = await response.json();
if (data && data[0]) {
const cat = data[0];
this.displayAnimal({
image: cat.url,
name: cat.breeds?.[0]?.name || 'Random Cat',
description: cat.breeds?.[0]?.description || 'A lovely cat',
type: 'Cat',
source: 'The Cat API'
});
} else {
throw new Error('Failed to fetch cat');
}
} catch (error) {
this.showError('Failed to fetch cat image');
}
// Fallback to random dog if cat API fails
if (!this.currentAnimal) {
await this.fetchDogAPI();
}
}
async fetchFoxAPI() {
try {
this.showLoading();
const response = await fetch('https://randomfox.ca/floof/');
const data = await response.json();
if (data.image) {
this.displayAnimal({
image: data.image,
name: 'Random Fox',
description: 'A cute fox in the wild',
type: 'Fox',
source: 'Random Fox API'
});
} else {
throw new Error('Failed to fetch fox');
}
} catch (error) {
this.showError('Failed to fetch fox image');
}
// Fallback to random dog if fox API fails
if (!this.currentAnimal) {
await this.fetchDogAPI();
}
}
async fetchRandomDogAPI() {
try {
this.showLoading();
const response = await fetch('https://api.thedogapi.com/v1/images/search');
const data = await response.json();
if (data && data[0]) {
const dog = data[0];
this.displayAnimal({
image: dog.url,
name: dog.breeds?.[0]?.name || 'Random Dog',
description: dog.breeds?.[0]?.description || 'A wonderful dog',
type: 'Dog',
source: 'The Dog API'
});
} else {
throw new Error('Failed to fetch dog');
}
} catch (error) {
this.showError('Failed to fetch dog image');
}
// Fallback to basic dog API if this fails
if (!this.currentAnimal) {
await this.fetchDogAPI();
}
}
async fetchRandomCatAPI() {
try {
this.showLoading();
const response = await fetch('https://api.thecatapi.com/v1/images/search?limit=1');
const data = await response.json();
if (data && data[0]) {
const cat = data[0];
this.displayAnimal({
image: cat.url,
name: cat.breeds?.[0]?.name || 'Random Cat',
description: cat.breeds?.[0]?.description || 'A lovely cat',
type: 'Cat',
source: 'The Cat API'
});
} else {
throw new Error('Failed to fetch cat');
}
} catch (error) {
this.showError('Failed to fetch cat image');
}
// Fallback to basic cat API if this fails
if (!this.currentAnimal) {
await this.fetchCatAPI();
}
}
extractBreedFromUrl(url) {
const parts = url.split('/');
const breedPart = parts[parts.length - 2];
return breedPart.split('-').map(word =>
word.charAt(0).toUpperCase() + word.slice(1)
).join(' ');
}
displayAnimal(animal) {
this.currentAnimal = animal;
this.viewCount++;
this.elements.animalImg.src = animal.image;
this.elements.animalImg.alt = animal.name;
this.elements.animalName.textContent = animal.name;
this.elements.animalDescription.textContent = animal.description;
this.elements.animalType.textContent = animal.type;
this.elements.animalSource.textContent = animal.source;
this.hideLoading();
this.elements.animalCard.classList.remove('hidden');
this.elements.errorMessage.classList.add('hidden');
this.updateStats();
}
showLoading() {
this.elements.loading.classList.remove('hidden');
this.elements.animalCard.classList.add('hidden');
this.elements.errorMessage.classList.add('hidden');
}
hideLoading() {
this.elements.loading.classList.add('hidden');
}
showError(message) {
this.elements.loading.classList.add('hidden');
this.elements.animalCard.classList.add('hidden');
this.elements.errorMessage.classList.remove('hidden');
this.elements.errorMessage.querySelector('p').textContent = message;
}
toggleFavorite() {
if (!this.currentAnimal) return;
const existingIndex = this.favorites.findIndex(fav =>
fav.image === this.currentAnimal.image
);
if (existingIndex !== -1) {
this.favorites.splice(existingIndex, 1);
} else {
this.favorites.push({
...this.currentAnimal,
addedAt: new Date().toISOString()
});
}
localStorage.setItem('animalFavorites', JSON.stringify(this.favorites));
this.updateStats();
this.renderFavorites();
}
updateStats() {
this.elements.viewCount.textContent = this.viewCount;
this.elements.favoriteCount.textContent = this.favorites.length;
}
renderFavorites() {
if (this.favorites.length === 0) {
this.elements.favoritesList.innerHTML = '<p class="no-favorites">No favorites yet. Start discovering animals!</p>';
return;
}
this.elements.favoritesList.innerHTML = this.favorites
.slice(-6) // Show last 6 favorites
.reverse() // Most recent first
.map(fav => `
<div class="favorite-item">
<img src="${fav.image}" alt="${fav.name}" loading="lazy">
<div class="favorite-info">
<h4>${fav.name}</h4>
<p>${fav.type} • ${fav.source}</p>
</div>
</div>
`).join('');
}
}
// Initialize the app when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
new RandomAnimalsApp();
});
// Add some fun animal facts for variety
const animalFacts = [
"Dogs have been domesticated for over 15,000 years!",
"Cats spend 70% of their lives sleeping.",
"Foxes are excellent swimmers and climbers.",
"Some dogs can smell cancer in humans.",
"Cats have over 20 muscles that control their ears.",
"Foxes use the Earth's magnetic field to hunt.",
"Dogs can understand up to 250 words and gestures.",
"Cats can rotate their ears 180 degrees.",
"Foxes are members of the dog family.",
"Dogs dream just like humans do!"
];
// Add random fact to description if available
function addRandomFact(description) {
const randomFact = animalFacts[Math.floor(Math.random() * animalFacts.length)];
return `${description} Fun fact: ${randomFact}`;
}