< BACK TO COMPONENTS

Create a Stunning Search Image App with HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn how to develop a Search Image App from scratch using HTML, CSS, JavaScript, and the Unsplash API. Follow our detailed guide for a seamless experience.


Create a Search Image App with HTML, CSS, and JavaScript.jpg

Are you ready to embark on a journey into the world of web development? In this comprehensive guide, we will take you through the step-by-step process of creating your very own Search Image App using HTML, CSS, and JavaScript, enriched with the magic of the Unsplash API. Whether you're a novice or an experienced developer, follow along, and by the end of this tutorial, you'll have a fully functional app at your fingertips.


Let's dive in and explore the exciting realm of web development as we craft a Search Image App that's not only visually appealing but also interactive and dynamic.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our search image app.


After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.


Let's break down the code step by step:


1. <!DOCTYPE html>: This is the document type declaration and specifies that the document is an HTML5 document.


2. <html lang="en">: This is the opening tag for the HTML document. The lang attribute is set to "en," indicating that the document is written in English.


3. <head>: The <head> section of an HTML document contains metadata about the page, such as character encoding, viewport settings, and the page's title.


  • <meta charset="UTF-8" />: This meta tag specifies the character encoding for the document, which is UTF-8, a widely used character encoding that supports various languages and special characters.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge" />: This meta tag is used to specify compatibility settings for Internet Explorer. It tells IE to use the latest rendering engine available.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0" />: This meta tag is crucial for responsive web design. It sets the viewport width to the device's width and establishes an initial zoom level of 1, ensuring that the page adapts well to various screen sizes.
  • <title>Image Search App</title>: This sets the title of the web page, which will be displayed in the browser's title bar or tab.
  • <link rel="stylesheet" href="styles.css" />: This line links an external stylesheet named "styles.css" to the HTML document. The stylesheet is used for defining the page's visual styles.

4. <body>: The <body> tag contains the visible content of the web page, including text, forms, buttons, and scripts.


5. <h1>Image Search App</h1>: This is a level 1 heading element that displays the title of the web application, "Image Search App."


6. <form>: This is an HTML form element. Inside the form, there are input fields and a button for user interaction.


  • <input type="text" id="search-input" placeholder="Search for images..." />: This is a text input field with the id "search-input" and a placeholder text instructing the user to "Search for images...". Users can type their search queries here.
  • <button id="search-button">Search</button>: This is a button element with the id "search-button." Clicking this button will trigger a search action, implemented using JavaScript.

7. <div class="search-results"></div>: This is an empty <div> element with the class "search-results." It's a placeholder for displaying search results. It may be populated dynamically using JavaScript.


8. <button id="show-more-button">Show more</button>: This is a button with the id "show-more-button." Clicking this button may trigger the display of additional search results or related content.


9. <script src="script.js"></script>: This line includes an external JavaScript file named "script.js." This JavaScript file contains the logic for handling user interactions, such as searching for images and updating the page content.


This is the basic structure of our search image app using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the search image app is in place, the next step is to add styling to the app using CSS.


Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our app.


Let's break down each section:


1. Styling for the body element:


  • background-color: Sets the background color of the entire page to a very light gray (#f9f9f9).
  • font-family: Specifies the font family for text content to be Arial, Helvetica, or sans-serif as a fallback.
  • line-height: Sets the line height for text to 1.6, which increases the spacing between lines.
  • margin: Sets the margin around the entire page to 0, removing any default spacing.

2. Styling for h1 headings:


  • font-size: Sets the font size of h1 elements to 36 pixels.
  • font-weight: Makes the text within h1 elements bold.
  • text-align: Centers the text within h1 elements horizontally.
  • margin-top and margin-bottom: Adds spacing above and below h1 elements, 40 pixels at the top and 60 pixels at the bottom.

3. Styling for form elements:


  • display: Changes the display property to flex to align form elements horizontally.
  • justify-content and align-items: Center-aligns the form elements both horizontally and vertically.
  • margin-bottom: Adds a margin of 60 pixels at the bottom of the form.

4. Styling for an element with id "search-input":


  • width: Sets the width of this element to 60% of its parent container, with a maximum width of 400 pixels.
  • padding: Adds 10 pixels of padding on the top and bottom and 20 pixels on the left and right.
  • border: Removes borders (set to "none").
  • box-shadow: Adds a slight shadow around the element.
  • border-radius: Rounds the corners of the element.
  • font-size: Sets the font size to 18 pixels.
  • color: Sets the text color to a dark gray (#333).

5. Styling for an element with id "search-button":


  • padding: Adds 10 pixels of padding on the top and bottom and 20 pixels on the left and right.
  • background-color: Sets the background color to a green color (#4caf50).
  • color: Sets the text color to white.
  • border: Removes borders (set to "none").
  • font-size: Sets the font size to 18 pixels.
  • box-shadow: Adds a slight shadow around the element.
  • cursor: Changes the cursor to a pointer (hand) when hovering.
  • border-radius: Rounds the corners of the element.
  • transition: Adds a smooth transition effect for background color changes on hover.

6. Styling for elements with class "search-results":


  • display: Sets the display property to flex to arrange child elements horizontally.
  • flex-wrap: Allows child elements to wrap to the next line if they exceed the container's width.
  • justify-content: Distributes child elements evenly along the horizontal axis.
  • max-width: Limits the maximum width of this container to 1200 pixels.
  • margin: Adds 20 pixels of margin on all sides.
  • padding: Adds 20 pixels of padding on all sides.

7. Styling for elements with class "search-result":


  • margin-bottom: Adds 60 pixels of margin at the bottom of each "search-result" element.
  • width: Sets the width of each "search-result" element to 30% of its parent container.
  • border-radius: Rounds the corners of each element.
  • box-shadow: Adds a slight shadow around each element.
  • overflow: Hides any content that overflows the "search-result" element.

8. Hover effect for "search-result" images:


  • When hovering over a "search-result" element, it enlarges the contained image by 5% using a smooth transition effect.

9. Styling for "search-result" images:


  • Sets the width to 100% of the parent container.
  • Limits the height to 200 pixels while maintaining aspect ratio.
  • Adds a smooth transition effect when scaling (hover effect).

10. Styling for "search-result" links (a elements):


  • Adds padding around the link.
  • Sets the text color to a dark gray (#333).
  • Adds a smooth background color transition on hover.

11. Styling for an element with id "show-more-button":


  • background-color: Sets the background color to a blue shade (#008cba).
  • border: Removes borders (set to "none").
  • color: Sets the text color to white.
  • padding: Adds 10 pixels of padding on the top and bottom and 20 pixels on the left and right.
  • display: Initially, the button is set to "none," so it is hidden.
  • margin: Centers the button horizontally with a margin of 20 pixels from the top.
  • text-align: Centers the text within the button.
  • border-radius: Rounds the corners of the button.
  • cursor: Changes the cursor to a pointer (hand) when hovering.
  • transition: Adds a smooth transition effect for background color changes on hover.

12. Media Queries:


  • Adjusts the styling of "search-result" elements when the screen width is less than 768 pixels, changing their width to 45%.
  • Adjusts the styling of "search-result" elements further when the screen width is less than 480 pixels, changing their width to 100% and modifying the form layout and input width.

This will give our search image app an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

body {
  background-color: #f9f9f9;
  font-family: Arial, Helvetica, sans-serif;
  line-height: 1.6;
  margin: 0;
}

h1 {
  font-size: 36px;
  font-weight: bold;
  text-align: center;
  margin-top: 40px;
  margin-bottom: 60px;
}

form {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 60px;
}

#search-input {
  width: 60%;
  max-width: 400px;
  padding: 10px 20px;
  border: none;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 5px;
  font-size: 18px;
  color: #333;
}

#search-button {
  padding: 10px 20px;
  background-color: #4caf50;
  color: white;
  border: none;
  font-size: 18px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  cursor: pointer;
  border-radius: 5px;
  transition: background-color 0.3s ease-in-out;
}

#search-button:hover {
  background-color: #3e8e41;
}

.search-results {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.search-result {
  margin-bottom: 60px;
  width: 30%;
  border-radius: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

.search-result:hover img {
  transform: scale(1.05);
}

.search-result img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  transition: transform 0.3s ease-in-out;
}
.search-result a {
  padding: 10px;
  display: block;
  color: #333;
  text-decoration: none;
  transition: background-color 0.3s ease-in-out;
}

.search-result:hover a {
  background-color: rgba(0, 0, 0, 0.1);
}

#show-more-button {
  background-color: #008cba;
  border: none;
  color: white;
  padding: 10px 20px;
  display: none;
  margin: 20px auto;
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease-in-out;
}

#show-more-button:hover {
  background-color: #0077b5;
}

@media screen and (max-width: 768px) {
  .search-result {
    width: 45%;
  }
}
@media screen and (max-width: 480px) {
  .search-result {
    width: 100%;
  }

  form {
    flex-direction: column;
  }

  #search-input {
    margin-bottom: 20px;
    width: 85%;
  }
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. It utilizes the Unsplash API to retrieve and display search results.


Let's break down the code step by step:


1. API Access Key: The accessKey variable holds an API access key. You would typically replace "YOUR UNSPLASH API" with your actual Unsplash API access key.


2. DOM Element Selection: Several variables are declared to select specific HTML elements from the page using JavaScript's document object model (DOM):


  • formEl: Represents a <form> element on the page.
  • searchInputEl: Represents an <input> element with the id "search-input".
  • searchResultsEl: Represents an HTML element with the class "search-results". This is a container where search results will be displayed.
  • showMoreButtonEl: Represents an HTML element with the id "show-more-button". This is probably a button that allows users to load more search results.

3. Data Storage: Two variables, inputData and page, are declared to store the search input and the current page number, respectively.


4. searchImages Function: This is an asynchronous function that performs the following tasks:


  • Retrieves the search input value from searchInputEl.
  • Constructs a URL for making a request to the Unsplash API, including the search query, page number, and API access key.
  • Uses fetch to make an asynchronous HTTP request to the Unsplash API.
  • Parses the JSON response from the API into a JavaScript object.
  • If it's the first page of results (page === 1), it clears the existing search results (searchResultsEl.innerHTML = "").
  • Iterates through the results, creating HTML elements for each image and its description, and appends them to the searchResultsEl.
  • Increments the page variable.
  • If page is greater than 1, it displays the "Show More" button.

5. Event Listeners:


  • An event listener is added to the <form> element (formEl) to listen for form submissions. When the form is submitted, it prevents the default form submission behavior, resets the page to 1, and calls the searchImages function to initiate a new search.
  • Another event listener is added to the "Show More" button (showMoreButtonEl). When the button is clicked, it calls the searchImages function again to load more search results.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

const accessKey = "YOUR UNSPLASH API";

const formEl = document.querySelector("form");
const searchInputEl = document.getElementById("search-input");
const searchResultsEl = document.querySelector(".search-results");
const showMoreButtonEl = document.getElementById("show-more-button");

let inputData = "";
let page = 1;

async function searchImages() {
  inputData = searchInputEl.value;
  if(inputData.trim()){
    const url = `https://api.unsplash.com/search/photos?page=${page}&query=${inputData}&client_id=${accessKey}`;

    const response = await fetch(url);
    const data = await response.json();
    if (page === 1) {
      searchResultsEl.innerHTML = "";
    }
  
    const results = data.results;
  
    results.map((result) => {
      const imageWrapper = document.createElement("div");
      imageWrapper.classList.add("search-result");
      const image = document.createElement("img");
      image.src = result.urls.small;
      image.alt = result.alt_description;
      const imageLink = document.createElement("a");
      imageLink.href = result.links.html;
      imageLink.target = "_blank";
      imageLink.textContent = result.alt_description;
  
      imageWrapper.appendChild(image);
      imageWrapper.appendChild(imageLink);
      searchResultsEl.appendChild(imageWrapper);
    });
  
    page++;
  
    if (page > 1) {
      showMoreButtonEl.style.display = "block";
    }
  }
}

formEl.addEventListener("submit", (event) => {
  event.preventDefault();
  page = 1;
  searchImages();
});

showMoreButtonEl.addEventListener("click", () => {
  searchImages();
});

Final Output:

Create a Search Image App with HTML, CSS, and JavaScript.gif

Conclusion:

Congratulations! You've now completed the journey of creating your own Search Image App using HTML, CSS, and JavaScript, with the added power of the Unsplash API. This accomplishment signifies a significant milestone in your web development skills.


With your newly acquired skills, you're now equipped to take on more complex web development projects and explore the endless possibilities of creating interactive web applications.


Remember that web development is an ever-evolving field. Keep experimenting, stay updated with the latest trends, and never stop learning. The knowledge you've gained here is just the beginning of an exciting journey in the world of web development.


We hope you've enjoyed this tutorial and found it both informative and practical. Feel free to customize and expand upon your Search Image App, adding your own unique features and designs. Your creativity knows no bounds in this dynamic field.


Thank you for joining us on this coding adventure. Happy coding, and may your future web projects be as amazing as the one you've just created!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post