File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 1+ async function fetchLatestXKCD ( ) {
2+ const apiEndpoint = 'https://xkcd.now.sh/?comic=latest' ;
3+
4+ try {
5+ const response = await fetch ( apiEndpoint ) ;
6+ if ( ! response . ok ) {
7+ throw new Error ( `Fetching error! Status: ${ response . status } ` ) ;
8+ }
9+
10+ const data = await response . json ( ) ;
11+ console . log ( 'Received data:' , data ) ;
12+
13+ if ( data . img ) {
14+ const imgElement = document . createElement ( 'img' ) ;
15+ imgElement . src = data . img ;
16+ imgElement . alt = data . alt || 'XKCD Comic' ;
17+
18+ const container = document . getElementById ( 'image-container' ) ;
19+ container . innerHTML = '' ;
20+ container . appendChild ( imgElement ) ;
21+ } else {
22+ console . warn ( 'No "img" property found in the data.' ) ;
23+ }
24+
25+ } catch ( error ) {
26+ console . error ( 'Error fetching data:' , error ) ;
27+ const errorMsg = document . createElement ( 'div' ) ;
28+ errorMsg . className = 'error' ;
29+ errorMsg . textContent = `Error fetching data: ${ error . message } ` ;
30+ document . body . appendChild ( errorMsg ) ;
31+ }
32+ }
33+
34+ fetchLatestXKCD ( ) ;
35+
You can’t perform that action at this time.
0 commit comments