diff --git a/lib/script.js b/lib/script.js index e69de29..e1d61c3 100644 --- a/lib/script.js +++ b/lib/script.js @@ -0,0 +1,20 @@ +let catAPI = "https://api.thecatapi.com/v1/images/search" +let randomCatButton = document.querySelector(".randomButton"); +let container = document.querySelector(".randomCatImage "); + +// fetch(catAPI) returns a random image, and passes it to display random cat as (randomCat) in part 2 +randomCatButton.addEventListener("click", displayRandomCat) +console.log(randomCatButton); +//part2 - WORKING - walked through via Noah +async function displayRandomCat(){ + //using await because the fetch is not instantaneous nor necessarily fast. It could take a while: + let request = await fetch(catAPI); + //using .json() to change the data being sent to a format js can interact with. must still use away as the original fetch may not be complete: + const randomCat = await request.json(); + console.log(randomCat); + //accessing the image object in an array sent by the server: + const imageURL = randomCat[0].url; + container.src = imageURL; + console.log('hi'); +} + diff --git a/lib/swapi_api_example b/lib/swapi_api_example new file mode 100644 index 0000000..8b15fce --- /dev/null +++ b/lib/swapi_api_example @@ -0,0 +1,43 @@ +const url = "https://swapi.dev/api/people"; +const form = document.querySelector("form"); +const h1 = document.querySelector("h1"); +const container = document.querySelector(".container"); + +form.addEventListener("submit", handleSubmit); + +function handleSubmit(e) { + e.preventDefault(); + + const { id } = e.target.elements; + + fetch(`${url}/${id.value}`) + .then((res) => res.json()) + .then((data) => { + displayCharacters(data); + }) + .catch((err) => console.log("oops something went wrong", err)); +} + +function displayCharacters(character) { + const characterHTML = ` +
Hair color: ${character.hair_color}
+Height: ${character.height}
+