30 Days Of JavaScript

Day 24: Banish Boredom

Lesson 3: Banish Boredom: 3

Let's add handlers for the buttons.

The easy one is the 'Nope' button, just show a new activity. So add this to your JavaScript:

1const onNopeClicked = () => {
2  onBoredClicked();
5const nopeButton = document.getElementById("nope-button");
6nopeButton.onclick = onNopeClicked;

Look at that for excellent code reuse!

Speaking of which, let's load a new activity when the page loads.

Add an onload handler that makes the same call. Add this to the end of your JavaScript file.

1window.onload = onBoredClicked;

Now that onBoredClicked is being called in two other places, we would be better off renaming it to fetchActivity and then calling it from onBoredClicked. This will be an exercise for the end. Leave it be for now.

Now for the like button. We want to save the activity to LocalStorage when it's clicked.

Thing is we can't access the data variable in the returned promise from an event handler we add to the like button, as they are in different scopes. So to get round that we add a new variable up the top to hold it for us. This is technically a global variable because of where we putting it, which is generally bad practice but we don't really have a choice here and it's fine in my opinion.

So add this to the top below all of the getElementById lines.

1let currentActivity;

And then in the second .then() add this line:

1currentActivity = data;

It should look like this now:

1.then((data) => {
2  console.log(data.link);
3  activity.innerText = data.activity;
4  type.innerText = data.type;
5  participants.innerText = data.participants;
6  price.innerText = data.price;
8  if (data.link.length) {
9    link.href = data.link;
10    linkContainer.hidden = false;
11  } else {
12    linkContainer.hidden = true;
13  }
15  currentActivity = data;

Now we can access currentActivity in the like handler 😀

Let's create and add our like click handler.

1const onLikeClicked = () => {
2  const savedActivitiesString = localStorage.getItem("activities");
4  const savedActivities = JSON.parse(savedActivitiesString) ?? [];
6  savedActivities.push(currentActivity);
8  localStorage.setItem("activities", JSON.stringify(savedActivities));
10  onBoredClicked(); // a forth place we call this!
13const likeButton = document.getElementById("like-button");
14likeButton.onclick = onLikeClicked;

Now click "Love it!" and check your LocalStorage (remember it's in Dev Tools then Application and then click on under Local Storage) to see a new property in there.

Now, how to load that!?


Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co