-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathmain.js
More file actions
75 lines (60 loc) · 1.68 KB
/
main.js
File metadata and controls
75 lines (60 loc) · 1.68 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
const baseUrl = 'https://dog.ceo/api/breeds';
const baseUrl2 = 'https://dog.ceo/api/breed';
const randomImg = document.querySelector('#random');
const rightSect = document.querySelector('.right-section');
const explore = document.querySelector('#explore');
const select = document.querySelector('#breeds');
const displayDogs = document.querySelector('.dogs-display');
function init() {
fetchRandomDog();
allDogBreeds();
}
function fetchRandomDog() {
fetch(`${baseUrl}/image/random`)
.then((res) => res.json())
.then((data) => {
rightSect.innerHTML = `<img
src=${data.message}
alt="doggo"
id="random"
/>`;
});
}
explore.addEventListener('click', fetchRandomDog);
function allDogBreeds() {
fetch(`${baseUrl}/list/all`)
.then((res) => res.json())
.then((data) => {
const breeds = Object.keys(data.message);
breeds.map((breed) => {
const option = document.createElement('option');
option.textContent = breed;
option.value = breed;
select.appendChild(option);
if (select.selectedOptions[0].value) {
fetchDogBreed(select.selectedOptions[0].value);
}
});
});
select.addEventListener('change', (e) => {
const selectedValue = e.target.value;
fetchDogBreed(selectedValue);
});
}
function fetchDogBreed(breed) {
fetch(`${baseUrl2}/${breed}/images`)
.then((res) => res.json())
.then((data) => {
const images = data.message.slice(0, 8);
displayDogs.innerHTML = '';
images.map((image) => {
const dog = document.createElement('div');
dog.className = 'dog-card';
const img = document.createElement('img');
img.src = image;
dog.appendChild(img);
displayDogs.appendChild(dog);
});
});
}
init();