-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
115 lines (75 loc) · 2.77 KB
/
app.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
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
// helper functions being used
function getHeight(height) {
return (parseInt(height,10)/10);
}
function getWeight(weight) {
return (parseInt(weight,10)/10);
}
function notFound() {
let pokemonName = document.querySelector('.name');
pokemonName.innerHTML =
` <p style="font-size: 40px; font-weight:bolder;padding: 10px">NOT FOUND</p>
<p style='padding: 10px'>Please check spelling and search again</p>
`
}
// function to display the retrieved data to the DOM
function displayData(data) {
let info = document.querySelector('.info');
let image = document.querySelector('.image');
let pokemonName = document.querySelector('.name');
info.innerHTML =
`<p><b>Pokedex ID :</b> ${data.id}</p>
<p><b>Type :</b> ${data.types[0].type.name.toUpperCase()}</p>
<p><b>Height :</b> ${getHeight(data.height)} m</p>
<p><b>Weight :</b> ${getWeight(data.weight)} kg</p>
<a href="https://www.pokemon.com/us/pokedex/${data.name}" target="_blank"><button>MORE</button></a>`
function getImageID(value) {
let lead = '000';
let pokeID = data.id;
let imageID = lead.slice(pokeID.toString().length) + data.id;
return imageID;
}
image.innerHTML =
`<img src="${`https://assets.pokemon.com/assets/cms2/img/pokedex/full/${getImageID(data.id)}.png`}" alt="image of pokemon" width="300px">`
pokemonName.innerHTML =
` <p style="font-size: 42px; font-weight:bolder;">${data.name.toUpperCase()}</p>`
}
// function to fetch the required data based on given seach input
function fetchData(data) {
let url = `https://pokeapi.co/api/v2/pokemon/${data}`;
fetch(url)
.then(function(response) {
if(response.status !== 200) {
notFound(); //function when response is 404 or something else
}
else {
return response.json();
}
})
.then(function(pokemonData) {
displayData(pokemonData);
})
}
// function to clear out search field
function clearData() {
let info = document.querySelector('.info');
let image = document.querySelector('.image');
let pokemonName = document.querySelector('.name');
info.innerHTML = '';
image.innerHTML = '';
pokemonName.innerHTML = '';
}
// checking to see if search button is triggered
function watchForm() {
let searchButton = document.querySelector('#search-button');
let searchForm = document.querySelector('#search-input');
searchForm.value = '';
searchButton.addEventListener('click', function(event) {
event.preventDefault();
event.stopPropagation();
clearData();
fetchData(searchForm.value.toLowerCase()); //sending searched item to fetchData function to get the data
searchForm.value = '';
});
}
watchForm();