|
| 1 | +/* |
| 2 | +Write a function that makes a HTTP Request to https://dog.ceo/api/breeds/image/random. 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. |
| 3 | +
|
| 4 | +Create an index.html file that will display your random image |
| 5 | +Add 2 <button> and 1 <ul> element, either in the HTML or through JavaScript |
| 6 | +Write two versions for the button functionality: one with XMLHttpRequest, and the other with axios |
| 7 | +When any one of the 2 buttons is clicked it should make a HTTP Request to https://dog.ceo/api/breeds/image/random |
| 8 | +After receiving the data, append to the <ul> a <li> that contains an <img> element with the dog image |
| 9 | +Incorporate error handling: log to the console the error message |
| 10 | +*/ |
| 11 | + |
| 12 | +//HTML elements: |
| 13 | +const galleryList = document.getElementById('gallery'); |
| 14 | +const xmlBtn = document.getElementById('xmlBtn'); |
| 15 | +const axiosBtn = document.getElementById('axiosBtn'); |
| 16 | +//API |
| 17 | +const url = 'https://dog.ceo/api/breeds/image/random'; |
| 18 | + |
| 19 | +//Getting dog image using XML: |
| 20 | +function getDogPicXML() { |
| 21 | + const xhr = new XMLHttpRequest(); |
| 22 | + xhr.responseType = 'json'; |
| 23 | + xhr.open('GET', url); |
| 24 | + |
| 25 | + xhr.onload = function () { |
| 26 | + if (xhr.status < 400) { |
| 27 | + const list = document.createElement('li'); |
| 28 | + galleryList.appendChild(list); |
| 29 | + const dogImg = document.createElement('img'); |
| 30 | + list.appendChild(dogImg); |
| 31 | + dogImg.src = xhr.response.message; |
| 32 | + } else { |
| 33 | + console.log('Error:', xhr.status); |
| 34 | + } |
| 35 | + }; |
| 36 | + |
| 37 | + xhr.onerror = function () { |
| 38 | + console.log('Something went wrong'); |
| 39 | + }; |
| 40 | + xhr.send(); |
| 41 | +} |
| 42 | + |
| 43 | +/* |
| 44 | +In all three excersises used different conditions to check xhr status, as there were given a lot of examples in reading and video materials, just to see if behavior would change. |
| 45 | +*/ |
| 46 | + |
| 47 | +//Getting dog image using axios: |
| 48 | +function getDogPicAxios() { |
| 49 | + axios |
| 50 | + .get(url) |
| 51 | + .then((response) => { |
| 52 | + const list = document.createElement('li'); |
| 53 | + galleryList.appendChild(list); |
| 54 | + const dogImg = document.createElement('img'); |
| 55 | + list.appendChild(dogImg); |
| 56 | + dogImg.src = response.data.message; |
| 57 | + }) |
| 58 | + .catch((err) => console.log(err)); |
| 59 | +} |
| 60 | + |
| 61 | +//Event listeners: |
| 62 | +xmlBtn.addEventListener('click', getDogPicXML); |
| 63 | +axiosBtn.addEventListener('click', getDogPicAxios); |
0 commit comments