Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions lib/script.js
Original file line number Diff line number Diff line change
@@ -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');
}

43 changes: 43 additions & 0 deletions lib/swapi_api_example
Original file line number Diff line number Diff line change
@@ -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 = `
<div>
<h1>${character.name}</h1>
<p>Hair color: ${character.hair_color}</p>
<p>Height: ${character.height}</p>
</div>
`;

container.insertAdjacentHTML("beforeend", characterHTML);
}
white_check_mark
eyes
raised_hands