1+ <!-- Exercise 3: Dog photo gallery
2+ Let's make a randomized dog photo gallery!
3+ Write a function that makes an API call to https://dog.ceo/api/breeds/image/random.
4+ It should trigger after clicking a button in your webpage. Every time the button is clicked it should append a new dog image to the DOM.
5+ Create an index.html file that will display your random image
6+ Add 2 <button> and 1 <ul> element, either in the HTML or through JavaScript
7+ Write two versions for the button functionality: one with XMLHttpRequest, and the other with axios
8+ When any one of the 2 buttons is clicked it should make an API call to https://dog.ceo/api/breeds/image/random
9+ After receiving the data, append to the <ul> a <li> that contains an <img> element with the dog image
10+ Incorporate error handling -->
11+
12+ <!DOCTYPE html>
13+ < html lang ="en ">
14+ < head >
15+ < meta charset ="UTF-8 " />
16+ < title > The Dog Photos Gallery</ title >
17+ < style >
18+ body {
19+ text-align : center;
20+ background-color : # 333 ;
21+ }
22+
23+ # buttons > button {
24+ padding : 20px ;
25+ margin : 30px 0 ;
26+ background-color : rgb (218 , 183 , 183 );
27+ color : # fff ;
28+ font-weight : bold;
29+ }
30+ # photoLine {
31+ display : flex;
32+ list-style : none;
33+ flex-wrap : wrap;
34+ }
35+ </ style >
36+ </ head >
37+ < body >
38+ < div id ="buttons ">
39+ < button id ="btn1 "> Touch to XHR for images</ button >
40+ < button id ="btn2 "> Touch to Axios for images</ button >
41+ </ div >
42+ < div id ="imgDiv ">
43+ < ul id ="photoLine "> </ ul >
44+ </ div >
45+ < script src ="https://unpkg.com/axios/dist/axios.min.js "> </ script >
46+ < script >
47+ const buttonForXhr = document . getElementById ( 'btn1' ) ;
48+ const buttonForAxios = document . getElementById ( 'btn2' ) ;
49+
50+ buttonForXhr . addEventListener ( 'click' , getImageWithXHR ) ;
51+ buttonForAxios . addEventListener ( 'click' , getImageWithAxios ) ;
52+
53+ function getImageWithXHR ( ) {
54+ const xhr = new XMLHttpRequest ( ) ;
55+ xhr . open ( 'GET' , 'https://dog.ceo/api/breeds/image/random' ) ;
56+ xhr . responseType = 'json' ;
57+ xhr . onload = ( ) => {
58+ displayImage ( xhr . response . message ) ;
59+ } ;
60+ xhr . send ( ) ;
61+ }
62+
63+ function getImageWithAxios ( ) {
64+ axios
65+ . get ( 'https://dog.ceo/api/breeds/image/random' )
66+ . then (
67+ res => {
68+ displayImage ( res . data . message ) ;
69+ } )
70+ . catch ( err => console . error ( err ) ) ;
71+ }
72+
73+ function displayImage ( imgAddress ) {
74+ const photoLine = document . getElementById ( 'photoLine' ) ;
75+ const img = document . createElement ( 'img' ) ;
76+ const li = document . createElement ( 'li' ) ;
77+ img . setAttribute ( 'src' , imgAddress ) ;
78+ img . style . width = '200px' ;
79+ img . style . height = '200px' ;
80+ li . appendChild ( img ) ;
81+ photoLine . appendChild ( li ) ;
82+ }
83+ </ script >
84+ </ body >
85+ </ html >
0 commit comments