1+ //Calling main function after window load
2+ window . onload = main ;
3+
4+ //Define main function
5+ function main ( ) {
6+ //Define button element
7+ const btn = document . createElement ( 'button' ) ;
8+ btn . textContent = 'start' ;
9+ btn . style . display = 'block' ;
10+ document . body . appendChild ( btn ) ;
11+
12+ // Define select element
13+ const select = document . createElement ( 'select' ) ;
14+ select . style . display = 'block' ;
15+ document . body . appendChild ( select ) ;
16+
17+ //Define image
18+ const img = document . createElement ( 'img' ) ;
19+
20+ //When button is clicked
21+ btn . addEventListener ( 'click' , ( ) => {
22+ const url = `https://pokeapi.co/api/v2/pokemon/?limit=20&offset=20` ; //Define API URL
23+ fetchData ( url , select , img ) ; // Get data from API and insert to DOM
24+ } ) ;
25+ }
26+
27+ // Add data to DOM
28+ function addPokemonToDOM ( data , select , img ) {
29+
30+ //Add list to select tag
31+ data . results . forEach ( element => {
32+ const option = document . createElement ( 'option' ) ;
33+ option . value = element . name ;
34+ option . textContent = element . name ;
35+ select . appendChild ( option ) ;
36+ } ) ;
37+
38+ //User selection
39+ select . addEventListener ( 'input' , ( ) => {
40+ data . results . forEach ( element => {
41+ if ( select . value == element . name ) {
42+ const imgURL = element . url ;
43+ fetch ( imgURL ) // second API request to get image
44+ . then ( function ( response ) {
45+ return response . json ( ) ;
46+ } )
47+ . then ( function ( myJson ) {
48+ img . src = myJson . sprites . back_default ;
49+ document . body . appendChild ( img ) ;
50+ } )
51+ . catch ( function ( error ) {
52+ console . log ( error ) ;
53+ } ) ;
54+ }
55+ } )
56+ } )
57+ } ;
58+
59+ //Get data from API by using fetch API
60+ function fetchData ( url , select , img ) {
61+ fetch ( url ) // First getting data
62+ . then ( function ( response ) {
63+ return response . json ( ) ;
64+ } )
65+ . then ( function ( myJson ) {
66+ addPokemonToDOM ( myJson , select , img ) ; // Add data to DOM
67+ } )
68+ . catch ( function ( error ) {
69+ console . log ( error ) ;
70+ } ) ;
71+ } ;
0 commit comments