Day 24: Banish Boredom
Lesson 2: Banish Boredom: 2
Remove console.log("hello");
.
First we will deal with making the network request to The Bored API when the button is clicked.
Add this code to your main.js.
1const onBoredClicked = () => { 2 console.log("bored"); 3}; 4 5const boredButton = document.getElementById("bored-button"); 6boredButton.onclick = onBoredClicked;
Click the button and check the logs to see bored
in them.
When setting up new projects or events I always do a little sanity check like this first. We could dive in and start writing the code we want in there, but if we mess up hooking the event up for whatever reason, you could (and I have) wasted a lot of time looking for a bug that can be solved by a quick test like this.
Now for the real code.
- Send GET request to The Bored API
- Display it in the card
Add this inside your onBoredClicked
function, click the button and then check the logs.
1fetch("https://www.boredapi.com/api/activity/") 2 .then((res) => res.json()) 3 .then((data) => { 4 console.log(data); 5 }) 6 .catch((error) => console.log(error));
The data structure matches the ids in the HTML card pretty well right?
1{ 2 "accessibility": 0.15, 3 "activity": "Take a class at your local community center that interests you", 4 "key": "8750692", 5 "link": "", 6 "participants": 1, 7 "price": 0, 8 "type": "education" 9}
Where we care about activity
, link
, participants
, price
and type
.
Let's add them to our card using getElementById()
.
Add these lines to the top of your JavaScript:
1const activity = document.getElementById("activity"); 2const type = document.getElementById("type"); 3const participants = document.getElementById("participants"); 4const price = document.getElementById("price"); 5const link = document.getElementById("link");
And then inside the same function as your console.log(data);
add these lines:
1activity.innerText = data.activity; 2type.innerText = data.type; 3participants.innerText = data.participants; 4price.innerText = data.price; 5link.innerText = data.link;
Now tap BORED
a few times and see the data change!
You may notice that Link looks a bit rubbish. Let's fix that!
If there is no link let's hide it and if there's a link let's make it a proper link.
Add this to the top of your JavaScript:
1const linkContainer = document.getElementById("link-container");
Then replace link.innerText = data.link;
with:
1if (data.link.length) { 2 link.href = data.link; 3 linkContainer.hidden = false; 4} else { 5 linkContainer.hidden = true; 6}
Now click a few times and you'll eventually see a link appear. If you're unsure if it's working then add a console.log(data.link)
to the function and you'll see it print a link when there is one.