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