Skip to content
Related Articles

Related Articles

Create a Gif Search Engine Using JavaScript
  • Difficulty Level : Medium
  • Last Updated : 28 Dec, 2020

In this article, we will create a Gif Search Engine using JavaScript. The basic application of Gif search Engine is to search the images from the given user input keywords and the output of the images will be loaded on the same page with different aspect ratios and sizes provided by Giphy. To get the output of the image we will use Giphy EndPoint Search API.  

By means of EndPoint in API, we are actually accessing the Giphy Images Delivering Services using the endpoint in our URL. 

Firstly we will create a HTML layout and style the elements using CSS. The Page contains the input field to  the search keywords for the images and some style it with CSS.

The basic HTML Layout presents the structure of the page and it includes the following-

  • Input Field: Basic Input field which accepts the alphanumeric keywords from user input.
  • Search Button: The Input keyword will be triggered to call the API method using this button.

    HTML



    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!DOCTYPE html>
    <html>
      <head>
        <title>Giphy Search Engine</title>
        <link rel="stylesheet" href="css/main.css" />
      </head>
      <body>
        <div class="header">
          <h1>Gif Search Engine</h1>
        </div>
        <div class="container container-padding50">
          <input type="text" class="js-userinput 
            container-textinput" />
          <button class="js-go container-button">
            Search!
          </button>
        </div>
        <div class="container 
          container-padding50 js-container">
        </div>
      
        <!-- Link to JavaScript File here-->
          
        <script src="javascript/main.js"></script>
      </body>
    </html>

    chevron_right

    
    

    In the given HTML Layout we have structured the above code in the following way

    HTML

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <style>
        
    body {
      width: 80%;
      max-width: 1024px;
      margin: 0 auto;
    }
      
    .header {
      padding: 100px 50px 50px 40px;
      position: relative;
      top: 50px;
    }
      
    h1 {
      font-weight: bold;
      font-style: normal;
      font-family: "Times New Roman";
      font-size: 72px;
      color: #090;
      text-align: center;
    }
      
    .container-padding50 {
      padding: 80px 0px 0px 30px;
    }
      
    .container-textinput {
      width: 70%;
      display: inline-block;
      padding: 16px;
      font-size: 20px;
      font-family: Helvetica, sans-serif;
    }
      
    .container-button {
      width: 20%;
      display: inline-block;
      padding: 16px;
      background-color: green;
      color: white;
      font-size: 20px;
      font-family: Helvetica, sans-serif;
      
      border: 1px solid green;
      border-radius: 5px;
    }
      
    .container-image {
      width: 30%;
      display: block;
      float: left;
      margin-right: 3%;
    }
      
    </style>

    chevron_right

    
    

  • A level-1 Heading tag used to display the title name and styled by defining the class as header using CSS.
  • Basic properties such as font-family, font-style, font-weight , color and alignment given to the classes to display the Heading.
  • In the next div container,  an input field and a button is displayed with classes to style with adequate Padding, width to make it aligned to the screen.
  • To load the output of the image in the same page a container is given with the bunch of styling properties such as  width and margin to scale all the images.
  • These classes and id’s can be modified later when required.

CSS Style: The created layout of the above HTML and CSS would look like this,

Main Logic of the Search Engine: Firstly, To enable the User Input keyword for searching the Gif images and showing them as output is written in a JavaScript File. There are a bunch of functions and logics to run the search Query.

There are several steps to follow along which would help to get the logic.

Step-1: Getting the Input from the User: Initially the input field have some keyword or value entered by the user which ensures that the logic would be performed on the given keyword. Here the keyword is selected by the query Selector method which then returns the Input keyword or a value. 

Javascript



filter_none

edit
close

play_arrow

link
brightness_4
code

function getUserInput() {
  var inputValue = document
    .querySelector(".js-userinput").value;
  return inputValue;
}

chevron_right


Step-2: Getting the Input and Processing the Request: Further, A set of operation is performed when the Search button is clicked. The value returned by the function `getUserInput` is now used by other functions as well. The value is then handled by handler for the click event. This can be achieved by adding EventListener method. Now whenever the Search button will be clicked a set of operation would perform on that Keyword. 

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

document.querySelector(".js-go").addEventListener("click", function () {
  var inputValue = document
    .querySelector(".js-userinput").value;
  var userInput = getUserInput();
  searchGiphy(userInput);
});

chevron_right


Note: There are other Events in the addEventListener method through which we can extend the ways of listening the events. Here “keyup” event is used to allow the user to press Enter and search the keyword for the images. In contrast, it actually listens which key user has pressed. Here an object is required to check whether the key pressed is matched to the KeyCode Value or not. 

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

document.querySelector(".js-userinput")
  .addEventListener("keyup", function (e) {
  
  // If the Key Enter is Pressed 
  if (e.which === 13) { 
    var userInput = getUserInput();
    searchGiphy(userInput);
  }
});

chevron_right


Step-3: Once the Input data is captured by the Event Listener it is now used by the searchGiphy function which takes the user data as a parameter and performs a set of operation.

searchGiphy( searchQuery ): The function handle the following things-

  • This function performs search operation everytime on the given user data and enable it by requesting the Giphy Server to return the Object using Giphy End Point Search API URL.
  • Giphy End Point Search API URL requests the Giphy server to response to the request and return the output in the form of JSON object.

Loading the Images without Refreshing the Page

  • The data returned by the Giphy API URL can be retrieved without refreshing the Page. We can achieve this by AJAX request to load the data without refreshing the page.
  • We can create a constructor of XMLHttpRequest(XHR) which initializes a GET request using .open( ) method and send the request by using .    .send()  method.
  • The response is then handled by the EventListener handler which is responsible to load the data on the screen.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

function searchGiphy(searchQuery) {
  var url =
  + searchQuery;
      
  // AJAX Request
    
  var GiphyAJAXCall = new XMLHttpRequest();
  GiphyAJAXCall.open("GET", url);
  GiphyAJAXCall.send();
  
  GiphyAJAXCall.addEventListener("load", function (data) {
    var actualData = data.target.response;
    pushToDOM(actualData);
    console.log(actualData);
      
  });
}

chevron_right


Step-4: A function pushToDOM is defined which will be responsible for processing the response and loading the Images.
pushToDOM(response): There are some standard steps to handle the responses from the API. This function handles the following things-

  • Accessing the Data The searchGiphy function receives the user data as a parameter and requests Giphy EndPoint Search API to access the query and return the response. 
     
  • Converting the responses to JSON Object The responses are basically arrays having Image label, type, source url, height, width and other information which can be retrieved by converting it into a JSON object.  By using JSON.parse(response) we can convert the object into JSON object.
     
  • Holding the responses By .querySelector method we select a container to hold the responses. If any previous responses are already synchronised and present in the container then just clear the container.
     
  • Image Rendition The output images have some properties which can be accessed by its object. By Rendition means, we actually want the url of the Image which can easily get by the .url method. 
     
  •  Display Image A container is needed to display an image, however an Image has an url which can be accessed by the container using the element property .innerHTML. 

Thus, we can process all the images in the responses by looping over the images which extract each image into a container with its source url.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

function pushToDOM(response) {
  
  // Turn response into real JavaScript object
  response = JSON.parse(response);
    
  // Drill down to the data array
  var images = response.data;
  
  // Find the container to hold the response in DOM
  var container = document.querySelector(".js-container");
    
  // Clear the old content since this function 
  // will be used on every search that we want
  // to reset the div
  container.innerHTML = "";
  
  // Loop through data array and add IMG html
  images.forEach(function (image) {
  
    // Find image src
    var src = image.images.fixed_height.url;
  
    // Concatenate a new IMG tag
    container.innerHTML += "<img src='" 
      + src + "' class='container-image' />";
  });
}

chevron_right


Final Output:

Source Code: https://github.com/codewithdev/Gif-Search-Engine 

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :