How to create a parallax website from scratch in 2019 – Part 3

how to create a parallax website 2019

Welcome to the third and final part of this series on how to create a parallax website from scratch in 2019.

On the first two parts we went over how to create the HTML portion of our parallax website, then we used some CSS in order to style it and now we’ll finally add some JavaScript to allow us to fetch data from an API and populate our page with dynamic content.

We’ll be using Teleport’s API in order to get the data we need.

Folder structure

Let’s jump right in and start by creating a folder called script and place a file called script.js inside that folder. This file will hold our JavaScript code.

Script folder and file for parallax website
Script folder and file for parallax website

Much like the css file shown on the second part of this series, we’ll have to make a reference to this file from our index.html like so:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="style/style.css" />

    <!-- HERE --><script src="script/script.js"></script>
  </head>

  <body>
    <div class="bgimg-1">
      <div class="caption">
        <span class="border">THE WANDERLUST</span>
      </div>
    </div>

    <div
      style="color: #777;background-color:white;text-align:center;text-align: justify;"
    >
      <h3 style="text-align:center;">Cities</h3>
      <div class="cities-container" id="cities"></div>
    </div>

    <div class="bgimg-2">
      <div class="caption">
        <span
          class="border"
          style="background-color:transparent;font-size:25px;color: #f7f7f7;"
          >TRAVEL</span
        >
      </div>
    </div>

    <div style="position:relative;">
      <div
        style="color:#ddd;background-color:#282E34;text-align:center;padding:50px 80px;text-align: justify;"
      >
        <p>
          Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis
          aliquid libero repellat consequuntur nihil similique quasi veniam
          magnam cum corporis cumque, ea neque perspiciatis temporibus quia
          perferendis quaerat? Porro, odit!
        </p>
      </div>
    </div>

    <div class="bgimg-3">
      <div class="caption">
        <span
          class="border"
          style="background-color:transparent;font-size:25px;color: #f7f7f7;"
          >SCROLL UP</span
        >
      </div>
    </div>

    <div style="position:relative;">
      <div
        style="color:#ddd;background-color:#282E34;text-align:center;padding:50px 80px;text-align: justify;"
      >
        <p>
          Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facilis
          aliquid libero repellat consequuntur nihil similique quasi veniam
          magnam cum corporis cumque, ea neque perspiciatis temporibus quia
          perferendis quaerat? Porro, odit!
        </p>
      </div>
    </div>
  </body>
</html>

After this comes the fun part! We can now add the code to that file.

JavaScript API request

The JavaScript code that I’ll show you does a few things(I left some handy comments on it to help you navigate the code):

  • First we define the API endpoint(the address where we will fetch our data) and set a variable to an empty array. This array will later hold the data returned from.
  • We then call the getRandomUrbanAreas() method, which will fetch the cities data from the API and randomly pick cities to add to our array. In order to get the images for these cities in this API, a separate request has to be made and that’s why we call the getImages() method.
  • The last step is to add those images to the screen and that is done by calling the addToScreen() method.
const urbanAreasEndpoint = "https://api.teleport.org/api/urban_areas/"
let urbanAreasImages = []
getRandomUrbanAreas(15)

/**
 * This function gets all images for the urban areas passed to it
 * @param {Array} urbanAreas Array of urban areas URLs and names
 * @param {Function} callback A function to be called once the images are gathered
 * @returns {Promise} Objects containing the name of an urban area and it's image
 */
function getImages(urbanAreas, callback) {
    urbanAreas.forEach(urbanArea => {
        fetch(urbanArea.href + "images/")
            .then((response) => {
                // Check if the request succeeded
                if (response.status !== 200) throw new Error('Looks like there was a problem. Status Code: ' + response.status)
                // Examine the text in the response
                return response.json()
            })
            .then((jsonResponse) => {
                callback({
                    name: urbanArea.name,
                    image: jsonResponse.photos[0].image.mobile
                })
            })
            .catch(err => console.error(err))
    })
}

/**
 * This function adds the urban area to the screen
 * @param {Array} urbanAreas 
 */
function addToScreen(urbanArea) {
    // Create span string
    let spanString = `
    <span class="card">
        <img src="${urbanArea.image}" alt="">
        <div class="overlay">
            <div class="text">${urbanArea.name}</div>
        </div>
    </span>
    `
    // Add span to cities div
    document.getElementById("cities").innerHTML += spanString
}

/**
 * This function gets all urban areas and returns a random x amount out of those
 * @param {Integer} x the amount of urban areas we want returned
 * @returns {Array} An array containing urban area objects
 */
function getRandomUrbanAreas(x) {
    fetch(urbanAreasEndpoint)
        .then((response) => {
            // Check if the request succeeded
            if (response.status !== 200) throw new Error('Looks like there was a problem. Status Code: ' + response.status)    
            // Examine the text in the response
            return response.json()
        })
        .then(data => {
            let images = []
            let max = data._links["ua:item"].length
            // Generate x random numbers
            for (let i = 0; i < x; i++) {
                let randomNumber = Math.floor(Math.random() * max)
                images.push(data._links["ua:item"][randomNumber])
            }
            return getImages(images, addToScreen)
        })
        .catch(function(err) {
            console.log('Fetch Error :-S', err)
    })
}

That piece of code does the job but there are MANY ways to improve it. After having a second look, I found some things that can be changed about that program but instead of fixing it right now, I’ll leave it up to you guys to improve on this code while you implement it.

I’ll write a piece on how to clean up your code later on, but for now this will be the end of our parallax website tutorial series.

Thanks a lot for reading,

Gásten Sauzande.

Leave a Reply

Your email address will not be published. Required fields are marked *