JavaScript Simple Random Cat Image Development Tutorial For Beginners

Are you looking to add a cute touch to your website by displaying random cat images? If so, you've come to the right place! In this article, the authors will discuss how to create an engaging feature that allows you to display random cat images using Vanilla JavaScript.

Utilizing pure JavaScript (Vanilla JavaScript) is an efficient way to add interactivity to your website without relying on external frameworks or libraries. The author will walk you through the step by step process of implementing this feature with simple yet effective JavaScript code.

In this tutorial, the author utilizes the API provided by thecatapi.com, which facilitates the generation of random cat images using JavaScript fetch in our application. For the appearance, the author uses CSS to make the website look attractive, elegant, and visually pleasing. The HTML code will be kept simple.

Tutorial

  1. First, create a folder named random-cat-image-js to facilitate our tutorial.
  2. Open your preferred text IDE.
  3. Create a file named index.html and save it in the random-image-cat-js folder.
  4. Here is the code :
  5. <!DOCTYPE html>
    <html>
      <head>
        <!-- Page title -->
        <title>Random Cat Image</title>
    
        <!-- Link to external CSS file -->
        <link rel="stylesheet" href="style.css" />
      </head>
    
      <body>
        <!-- Container to hold the button and image -->
        <div class="container">
          <!-- Button to fetch new random cat image -->
          <button type="button" class="btn-cat">New Random Cat</button>
    
          <!-- Image container to display the random cat image -->
          <div class="image-container" id="img_cat"></div>
        </div>
    
        <!-- Script to import the JavaScript file -->
        <script src="script.js"></script>
      </body>
    </html>

  6. For the CSS code, create a file named style.css and save it in the random-cat-image-js folder.
  7. Here is the code :
  8. /* Apply font-family 'Arial, sans-serif' to the entire body */
    body {
      font-family: Arial, sans-serif;
    
      /* Use flexbox to horizontally and vertically center the content */
      display: flex;
      justify-content: center;
      align-items: center;
    
      /* Set the height of the body to occupy the full viewport height */
      height: 100vh;
    
      /* Remove default margin to ensure content is centered properly */
      margin: 0;
    
      /* Set the background color of the body to #f8f8f8 */
      background-color: #f8f8f8;
    }
    
    /* Center the content inside the container */
    .container {
      text-align: center;
    }
    
    /* Style for the 'New Random Cat' button */
    .btn-cat {
      /* Set the background color to #007bff (blue) */
      background-color: #007bff;
    
      /* Set the text color to white (#fff) */
      color: #fff;
    
      /* Set the font size to 18 pixels */
      font-size: 18px;
    
      /* Add padding of 12 pixels on the top and bottom, and 24 pixels on the left and right */
      padding: 12px 24px;
    
      /* Remove the default border */
      border: none;
    
      /* Add rounded corners to the button */
      border-radius: 5px;
    
      /* Change the cursor to a pointer when hovering over the button */
      cursor: pointer;
    }
    
    /* Add a top margin of 20 pixels to the image container */
    .image-container {
      margin-top: 20px;
    }

  9. Result, when the author open the index.html file :
  10. Then, create script.js and save into random-cat-image-js folder.
  11. Here is the javascript code :
  12. let btn_cat = document.querySelector(".btn-cat");
    let img_cat = document.getElementById("img_cat");
    let url = "https://api.thecatapi.com/v1/images/search";
    
    btn_cat.addEventListener("click", function () {
      fetch(url)
        .then((response) => response.json())
        .then((data) => {
          img_cat.innerHTML = `<img src=${data[0].url} alt="cat" style="width:100%; height:350px;"/>`;
        });
    });

    Step by step explanation of the JavaScript code provided:

    Initialize variables:
    let btn_cat = document.querySelector(".btn-cat");
    let img_cat = document.getElementById("img_cat");
    let url = "https://api.thecatapi.com/v1/images/search";

    - The btn_cat variable holds the element with the class "btn-cat." It is assumed that this element is a button that will be used to trigger the request for a random cat image.

    - The img_cat variable holds the element with the id "img_cat." This element is where the cat image will be displayed.

    - The url variable contains the API endpoint URL from where we will fetch the random cat image.

    Event listener for the button:
    btn_cat.addEventListener("click", function () {
      // ...
    });

    - When the button with the class "btn-cat" is clicked, the callback function will be executed to fetch and display a random cat image.

    Fetching data from the API:
    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        // ...
      });

    - The fetch() function is used to make a network request to the API specified in the url variable. It returns a Promise that resolves to the Response object.

    - The first .then() method is used to handle the response. It converts the raw response data into a JSON format using response.json() and returns another Promise.

    - The second .then() method is used to handle the parsed JSON data. The data variable contains the response data, which will be an array of objects, each representing a random cat image.

    Displaying the cat image:
    img_cat.innerHTML = `<img src=${data[0].url} alt="cat" style="width:100%; height:350px;"/>`;

    - Inside the second .then() block, we access the first object in the data array (since the response data is an array) using data[0].

    - From this object, we extract the URL of the cat image using data[0].url, which will be displayed in the img_cat element.

    - The cat image is displayed as an HTML img element with the specified URL, alt text "cat," and inline styles to set its width and height.

    In summary, the provided JavaScript code fetches a random cat image from "https://api.thecatapi.com/v1/images/search" when the "btn-cat" button is clicked and displays the image in the "img_cat" element. The cat image is fetched from the API and then rendered into the HTML page using JavaScript.

  13. Result :
  14. Done.

Closing

The author hopes you enjoy this tutorial and that it helps you enhance your knowledge in JavaScript.