HomeJavascriptGif Search App Javascript

Gif Search App Javascript

Welcome to yet another exciting tutorial by Coding Artist. Building projects is one of the best ways to learn Javascript. So in today’s tutorial let us expand our javascript knowledge with a fun and easy-to-build project called ‘Gif search app’. To build this project we need HTML, CSS, Javascript, and the Giphy API.

Video Tutorial:

For a better understanding of how we built the functionality of this project, I would advise you to watch the video below. If you find the video helpful give it a like and subscribe to my YouTube channel where I post new tips, tricks, and tutorials related to HTML, CSS, and Javascript.

Project Folder Structure:

Let’s build the project folder structure before we begin writing the code. We create a project folder called ‘Gif search app’. Inside this folder, we have index.html, style.css, script.js, and API-key.js.

HTML:

We begin with the HTML Code. First, create a file called – ‘index.html’. Copy the code below and paste it into your HTML file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Gif Search App</title>
    <!-- Google Font -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@500&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="box">
      <div class="search-container">
        <input type="text" id="search-box" value="laugh" />
        <button id="submit-btn">Submit</button>
      </div>
      <div class="loader"></div>
      <div class="wrapper"></div>
    </div>
    <!-- API Key -->
    <script src="api-key.js"></script>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Next, we style our list using CSS. For this copy, the code provided to you below and paste it into your stylesheet.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}
body {
  background-color: #151d2f;
}
button {
  border: none;
  outline: none;
  cursor: pointer;
  background-color: #13fc97;
  color: #151d2f;
  border-radius: 0.5em;
  font-weight: 500;
}
.search-container {
  display: grid;
  grid-template-columns: 9fr 3fr;
  gap: 1em;
  width: 100%;
  max-width: 50em;
  margin: 1em auto;
  padding: 0.5em;
}
.search-container input {
  padding: 1em;
  border-radius: 0.5em;
  font-weight: 400;
}
.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}
.container {
  background-color: #2b304d;
  display: flex;
  padding: 1em;
  flex-direction: column;
  justify-content: space-between;
  margin: 1.5em;
  border-radius: 0.5em;
}
.container img {
  width: 100%;
}
.container button {
  margin-top: 1em;
  padding: 1em 0;
}
.loader {
  display: none;
  height: 15em;
  width: 15em;
  border: 3em solid #2b304d;
  border-radius: 50%;
  border-top-color: #13fc97;
  position: absolute;
  transform: translate(-50%, -50%);
  left: 50%;
  top: 50%;
  animation: spin 3s infinite;
}
@keyframes spin {
  100% {
    transform: translate(-50%, -50%) rotate(360deg);
  }
}
@media screen and (max-width: 768px) {
  .wrapper {
    grid-template-columns: repeat(2, 1fr);
  }
  .container {
    margin: 0.7em;
  }
}
@media screen and (max-width: 576px) {
  .wrapper {
    grid-template-columns: 1fr;
  }
}

Javascript:

Finally, we add functionality using Javascript. Once again copy the code below and paste it into your script file.

Before moving to actual implementation we store the API key in the file ‘api-key.js’.

Then let’s move on to the implementation steps:

  • Create initial HTML references and store the API URL in a variable
  • Call the “generateGif()” function when the user clicks on the submit button or when the window loads
  • The “generateGif()” function displays a loader until all the GIFs have loaded and makes a call to the Giphy API based on the search value or default value.
  • After that, we create a card for each gif we get in response. The card displays the gif and a copy link button that allows the user to copy a link to the GIF to their clipboard.
  • If the user’s browser does not support the clipboard API, we create a temporary input field to copy the GIF link to the clipboard.
//Paste the generated API Key here
let apiKey = "";
let submitBtn = document.getElementById("submit-btn");

let generateGif = () => {
  //display loader until gif load
  let loader = document.querySelector(".loader");
  loader.style.display = "block";
  document.querySelector(".wrapper").style.display = "none";

  //Get search value (default => laugh)
  let q = document.getElementById("search-box").value;
  //We need 10 gifs to be displayed in result
  let gifCount = 10;
  //API URL =
  let finalURL = `https://api.giphy.com/v1/gifs/search?api_key=${apiKey}&q=${q}&limit=${gifCount}&offset=0&rating=g&lang=en`;
  document.querySelector(".wrapper").innerHTML = "";

  //Make a call to API
  fetch(finalURL)
    .then((resp) => resp.json())
    .then((info) => {
      console.log(info.data);
      //All gifs
      let gifsData = info.data;
      gifsData.forEach((gif) => {
        //Generate cards for every gif
        let container = document.createElement("div");
        container.classList.add("container");
        let iframe = document.createElement("img");
        console.log(gif);
        iframe.setAttribute("src", gif.images.downsized_medium.url);
        iframe.onload = () => {
          //if iframes has loaded correctly reduce the count when each gif loads
          gifCount--;
          if (gifCount == 0) {
            //If all gifs have loaded then hide loader and display gifs UI
            loader.style.display = "none";
            document.querySelector(".wrapper").style.display = "grid";
          }
        };
        container.append(iframe);

        //Copy link button
        let copyBtn = document.createElement("button");
        copyBtn.innerText = "Copy Link";
        copyBtn.onclick = () => {
          //Append the obtained ID to default URL
          let copyLink = `https://media4.giphy.com/media/${gif.id}/giphy.mp4`;
          //Copy text inside the text field
          navigator.clipboard
            .writeText(copyLink)
            .then(() => {
              alert("GIF copied to clipboard");
            })
            .catch(() => {
              //if navigator is not supported
              alert("GIF copied to clipboard");
              //create temporary input
              let hiddenInput = document.createElement("input");
              hiddenInput.setAttribute("type", "text");
              document.body.appendChild(hiddenInput);
              hiddenInput.value = copyLink;
              //Select input
              hiddenInput.select();
              //Copy the value
              document.execCommand("copy");
              //remove the input
              document.body.removeChild(hiddenInput);
            });
        };
        container.append(copyBtn);
        document.querySelector(".wrapper").append(container);
      });
    });
};

//Generate Gifs on screen load or when user clicks on submit
submitBtn.addEventListener("click", generateGif);
window.addEventListener("load", generateGif);

Go ahead and customize the project the way you like. If you have any queries, suggestions, or feedback comment below. Download the source code by clicking the ‘Download Code’ button below.

RELATED ARTICLES

2 COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here

1 × 4 =

Most Popular