Skip to main content

Build Image Search App with JavaScript

In our previous tutorial, we have explained how to build Barcode Generator with JavaScript. In this tutorial, we will explain how to make Image Search App with JavaScript.

Image search is a common functionality that allows user’s to find images. The image search can be based on keywords.

Here in this tutorial, we will create a user freindly interface to search images usign keywords. We will implement image functionality with JavaScript by using Unsplash API.

So let’s proceed with coding:

1. Include Required Library and Files

First we will create a HTML file index.html and include required CSS and JavaScript files.

<link rel="stylesheet" href="./css/all.min.css" />
<link rel="stylesheet" href="./css/bootstrap.min.css" />
<link rel="stylesheet" href="./css/style.css" />

<script src="./js/bootstrap.bundle.js"></script>
<script src="./js/jquery-3.7.0.min.js"></script>
<script src="./js/search.js"></script>

2. Create Image Search Section

We will create HTML for image search section with an input and a button to search for images usign keywords.

<header>     
  <div class="container">
	<div class="caption text-center">
	  <br>
	  <h1 class="mb-5 mt-5 mt-md-0">Image Search Application with JavaScript</h1>
	</div>
	<div
	  class="search d-flex justify-content-center align-items-center gap-2"
	>
	  <input
		id="searchInput"
		type="text"
		class="form-control"
		placeholder="Search for images"
	  />
	  <button class="btn btn-main" id="searchBtn">Search</button>
	</div>
  </div>
</header>

We will also create HTML to list search results with show more result button.

<main>
  <section id="imgs" class="pt-5">
	<div class="container">
	  <div class="row g-4" id="inputResults">
		
	  </div>
	  <div class="d-flex justify-content-center mt-5">
		<button class="btn btn-main mx-auto d-none" id="showMore">
		  Show more
		</button>
	  </div>
	</div>
  </section>
</main>

3. Implement Image Search with API

We will create JavaScript file search.js and implement searchImages() function to search image by making API request to unsplash api. We will also call function displaySearchResult() to list image search result.

let searchInput = "";
  let page = 1;
  let data = [];

  async function searchImages() {
    const accessKey = "API ACCESS KEY";
    const url = `https://api.unsplash.com/search/photos?page=${page}&query=${searchInput}&client_id=${accessKey}`;
    const searchApi = await fetch(url);
    const apiResponse = await searchApi.json();

    if (!apiResponse.error) {
      if (page === 1) {
        data = apiResponse.results;
      } else {
        data = data.concat(apiResponse.results);
      }
      displaySearchResult();
    }
  }

We will implement function displaySearchResult() to list search result.

function displaySearchResult() {
	let searchResults = "";
	if (data.length === 0) {
	  searchResults = "<p class='text-center fw-bold'>No results found.</p>";
	} else {
	  for (let i = 0; i < data.length; i++) {
		searchResults += `
		  <div class="col-md-6 col-lg-4">
			<div class="card searchImg">
			<div id="cardImg">
			   <img
				src="${data[i].urls.small}"
				class="card-img-top"
				alt="${data[i].alt_description}"
				/></div>
			   <div class="card-body">
				<a
				  href="${data[i].links.html}"
				  class="card-text"
				  target="_blank"
				  rel="noopener"
				  >${data[i].alt_description}</a
				>
			   </div>
			 </div>
		  </div>`;
	  }
	}
	$("#inputResults").html(searchResults);

	if (data.length > 0) {
	  $("#showMore").removeClass("d-none");
	} else {
	  $("#showMore").addClass("d-none");
	}
}

We will implement function performSearch() and call function searchImages(). Then we will call function performSearch() with search events to search images.

function performSearch() {
	searchInput = $("#searchInput").val();
	searchImages();
}

$("#searchInput").on("keyup", function (event) {
	if (event.key === "Enter") {
	  page = 1;
	  performSearch();
	}
});

$("#searchBtn").on("click", function () {
	page = 1;
	performSearch();
});

$("#showMore").on("click", function () {
	page++;
	if (searchInput == $("#searchInput").val()) {
	  performSearch();
	} else {
	  searchImages();
	}
});

You can view the live demo and download the complete source code of this project.
Demo Download