Building a cat image generator with Unsplash 😻
Tags: beginners, learning, javascript, es6
Published: 2019-01-19 22:51:18

---
title: Building a cat image generator with Unsplash 😻
published: true
description: An Unsplash image generator worthy of our cat overlords
tags: Beginners, learning, JavaScript, ES6
cover_image: https://source.unsplash.com/CVS4kWJaYLs/1000x420
---

Cover image by [@kivenzhao](https://unsplash.com/@kivenzhao)

Are you a playful learner? You should be! Play opens your mind to creativity and may help you enter a [flow state](https://en.wikipedia.org/wiki/Flow_(psychology)). I’m new to programming so approaching learning from a playful place reduces frustration and lengthens my practice sessions. 

I’m writing this post for other newbies to show them how a project can be made fun. As a newbie I love articles that include resources for further reading so I’ve made sure to include them throughout!

Before we dive into the code go ahead and click the shuffle button below to see Cats of Unsplash in action 👇

{% codepen https://codepen.io/mandihamza/pen/JwGLez %}

I had three goals for this project: learn about Javascript functions, For...of loops, and keep it playful, with cats!

**Plan your work. Work your plan.**

A cat-image generator needs four things:

**1 . A home for your code** ✔️

[Codepen](https://codepen.io/) is a popular browser based code editor that is super newbie friendly. It’s the perfect place for a project like *Cats of Unsplash*. Also, it has a hot reloading feature, so everytime I changed my code a new set of cat pictures appeared! This helped keep a smile on my face even when I was struggling.

**2.  Beautiful cat photos** ✔️

[Unsplash](http://unsplash.com/) has amazing photographers who share free high-quality images. Their [Unsplash Source](https://source.unsplash.com/) tool serves random images and offers basic query parameters. It’s perfect for small low-traffic projects. If you're building a high-traffic app and need robust parameters you should use their [free API](https://unsplash.com/developers).

**3. A Little design** ✔️

When I was little, I loved the bright colors Lisa Frank used.  I used that as inspiration for the colorful background. I used this [CSS gradient generator tool](https://cssgradient.io/) to help pick the bright colors. I love tools that make design a little easier! The images are styled using CSS grid, but I'm not going into great detail about the style because the focus for this post is Javascript.

**4. Some code** ✔️

The HTML markup requires 3 image elements with src tags and one button element:

```html
<button id="shuffleButton" type="button" class="button" alt="Shuffle Button">Shuffle</button>


<div class="grid">
  <img class="cube" src="" alt="cat picture">
  <img class="cube" src="" alt="cat picture">
  <img class="cube" src="" alt="cat picture">
</div>
```

We need a function to request URL responses from Unsplash. Here are the core elements:

1. A constant to hold the URL from Unsplash Source with some parameters.
2. A constant to hold the img elements.
3. A constant to hold a random number generator. We’ll use it to append unique signatures to each URL request. (You'll see why we need this in a minute.)
4. A For...of loop to iterate through the img elements and modify their src values.


First, lets declare our URL constant. This is the complete URL constant for *Cats of Unsplash*:

```javascript
const url = "https://source.unsplash.com/collection/139386/200x200/?sig=";
```

Here is a breakdown of the URL:

1. The base URL from Unplash: [https://source.unsplash.com/](https://source.unsplash.com)
2. The `collection` parameter followed by the unique [collection](https://unsplash.com/collections) number. 
For example,  I used a collection of cat images curated by [@dylka](https://unsplash.com/@dylka). 

    The URL for this collection is: [https://unsplash.com/collections/139386/cats](https://unsplash.com/collections/139386/cats). 

    We need the number for our URL: `139386` 

3. The image size parameter: `200x200`.
4. The sig parameter: `?sig=`.

Next, lets declare the constant that holds the img elements, like this:

```javascript
const images = document.querySelectorAll("img");
```

Now lets declare a constant to hold the [random number generator](https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/generate-random-whole-numbers-with-javascript/). We’ll use it to append a unique number after the sig parameter each time we make a new request.

We need this because the browser tries to *help* by serving a cached copy of the URL response from Unsplash instead of a fresh response. This is usually [helpful behavior](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching), but in this case it results in duplicate images. The unique numeric signature forces the browser to make a fresh request and is otherwise [ignored on the server-side](https://github.com/unsplash/unsplash-source-js/issues/9). There are still occasional duplicate images, but the frequency is greatly reduced.

```javascript
const randomNum = () => {
  return Math.floor(Math.random() * 1000);
};
```


Now lets create a function that iterates over the img elements and populates each img src attribute value with a random Unsplash URL using the constants we declared. Here’s how the code looks:

```javascript
function shufflePics() {
  for (let att of images) {
    att.src = `${url}${randomNum()}`;
    {
      console.log(att.src);
    }
  }
}
```

I used a For...of loop to iterate over the img elements because it can iterate over NodeList Objects, which is what the querySelectorAll() method returns for our image constant. There are other ways to iterate over NodeList Objects, but as a beginner I find the For...of loop easy to read.

The images constant holds the image elements, but to access their src attribute values we need to use Dot Notation, like this: `att.src`. 

Now we need to a assign the URL and randomNum constants to `att.src`. We wrap them like this, `${}` - which is called an expression in ES6. Expressions are placeholders for the strings they contain (the URL & random number). Then the expressions are wrapped in backticks to combine them into one string.

Now, the function populates each src attribute value with a unique URL response from Unsplash. Yay! 🥳

Last, we need to tie the button to the shufflePics function so it fetches three new cat pics with each click. We do this by selecting the button with the `querySelector()` method and adding an event listener. The code looks like this:

```javascript
document.querySelector("button").addEventListener("click", shufflePics);
```

That's it! Now we can shuffle endlessly through the cat pics from this Unsplash collection!


Next time you begin a tutorial or side project, I invite you to be playful! It will open your mind to new possibilities and, if you’re anything like me, it will help keep you focused.

Making *Cats of Unsplash* was super fun and I can’t wait to improve it! I'm excited to learn how to use Unsplash’s API so my next iteration displays the credits for the wonderful photographers.

Thank you for reading my very first Dev.to post! I look forward to your feedback about my code, our cat overlords, and how you incorporate playfulness into your work. 

***-Mandi Hamza***

Feel free to give me shout on [Twitter](https://twitter.com/_technicallyme)!

P.S. Not a cat person? Try [Dogs of Unsplash](https://codepen.io/mandihamza/pen/pqdPWm) 🐶

**As promised, here are some resources for further reading.**

This tutorial by Sheelah Brennan helped get me going on this project. I highly recommend checking it out!
• ✨[How to Automate Pulling in Random Images from Unsplash for Prototypes](https://sheelahb.com/blog/unsplash-random-image-how-to/).✨ 


**Understanding For...of Loops**
    • [5 ways to loop over DOM elements from querySelectorAll in JavaScript](https://medium.com/@jsdevray/5-ways-to-loop-over-dom-elements-from-queryselectorall-in-javascript-55bd66ca4128)
    • [Moz documentation on Loops and iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement)


**Understanding template literal syntax**
    • [A guide to Javascript template literals](https://flaviocopes.com/javascript-template-literals/) by Flavio Copes
    • [Template strings](https://wesbos.com/template-strings-html/) by Wes bos
    • [Moz documentation on template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)
    • [Switching to ES6 (Part 2: String Interpolation and Template Literals)](https://medium.com/predict/switching-to-es6-part-2-string-interpolation-and-template-literals-2f1b0ee56740)

**Understanding const vs. var vs. let**
    • [How let and const are scoped in JavaScript](https://wesbos.com/javascript-scoping/) by Wes bos

**Misc.**
• [JavaScript: Arrow Functions for Beginners](https://codeburst.io/javascript-arrow-functions-for-beginners-926947fc0cdc)
• [Moz documentation on HTTP caching](https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching)
• [$(document).ready() vs window.onload() vs $(window).load()](https://www.techiediaries.com/javascript/document-ready-vs-window-onload-vs-window-load/)