Skip to content

Commit b8df810

Browse files
committed
Ex3
1 parent 5c5c993 commit b8df810

3 files changed

Lines changed: 79 additions & 0 deletions

File tree

‎Week2/homework/masoud/js-exercises/Ex3-gottaCatchEmAll.js‎

Whitespace-only changes.
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<meta charset="UTF-8">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<title>pokemon</title>
8+
</head>
9+
10+
<body>
11+
12+
<script src="script.js"></script>
13+
</body>
14+
15+
</html>
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
//Calling main function after window load
2+
window.onload = main;
3+
4+
//Define main function
5+
function main(data) {
6+
// Define input element
7+
const input = document.createElement('input');
8+
input.type = 'number';
9+
input.min = '1';
10+
input.max = '895';
11+
input.style.width = '110px';
12+
input.placeholder = 'Insert a number';
13+
document.body.appendChild(input);
14+
15+
//Define button element
16+
const btn = document.createElement('button');
17+
btn.textContent = 'start';
18+
btn.style.display = 'block';
19+
document.body.appendChild(btn);
20+
21+
//When button is clicked
22+
btn.addEventListener('click', () => {
23+
if (input.value > 0 && input.value < 896) { //Check input
24+
const url = `https://pokeapi.co/api/v2/pokemon/${input.value}`;//Define API URL
25+
fetchData(url); // Get data from API and insert to DOM
26+
} else {
27+
alert('Your input number must be between 0 and 895!')
28+
};
29+
});
30+
};
31+
32+
// Add data to DOM
33+
function addPokemonToDOM(data) {
34+
// Define img element
35+
const imgSRC = data.sprites.back_default
36+
const image = document.createElement('img');
37+
image.src = imgSRC;
38+
document.body.appendChild(image);
39+
//disapear img element after 1.5 second
40+
window.setTimeout(() => {
41+
document.body.removeChild(image);
42+
}, 1500);
43+
};
44+
45+
//Get data from API by using fetch API
46+
function fetchData(url) {
47+
fetch(url) // First getting data
48+
.then(function (response) {
49+
return response.json();
50+
})
51+
.then(function (myJson) {
52+
addPokemonToDOM(myJson); // Add data to DOM
53+
return fetch(url); //Second getting data
54+
})
55+
.then((response => {
56+
return response.json();
57+
}))
58+
.then((myJson) => {
59+
addPokemonToDOM(myJson);// Add data to DOM
60+
})
61+
.catch(function (error) {
62+
console.log('error:' + error);
63+
});
64+
};

0 commit comments

Comments
 (0)