Create a Music Search App using HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn how to build a simple music search app using HTML, CSS, and JavaScript with iTunes integration. This step-by-step guide will help you create your own music search app.


create-a-music-search-app-using-html-css-and-javascript.webp

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

In this tutorial, we will guide you through creating a Music Search App using HTML, CSS, and JavaScript, with integration to iTunes for fetching music data. This is a great project for beginners looking to practice their front-end development skills while building a functional and interactive app. You’ll learn how to use iTunes as a data source to enhance the search functionality of your app.

Prerequisites:

Before starting, make sure you have:

  1. Basic knowledge of HTML, CSS, and JavaScript.
  2. A code editor (e.g., Visual Studio Code or Sublime Text).
  3. A browser to test your app (e.g., Google Chrome).

In this tutorial, you will:

  • Create the structure of the app using HTML.
  • Style the app with CSS to make it visually appealing.
  • Use JavaScript to fetch music data from iTunes and display it in the app.

Source Code

Step 1 (HTML Code):

Start by creating the basic structure of the app. Open your code editor and create an index.html file. Here's an explanation of the HTML code:

Structure of the HTML Document

  1. <!DOCTYPE html>:
    • Declares the document as an HTML5 document, ensuring the browser interprets the code as HTML5.
  2. <html lang="en">:
    • The <html> element is the root of the document.
    • The lang="en" attribute specifies the language of the document as English, helping search engines and screen readers.

Head Section

The <head> contains metadata and links to external resources.

  1. <meta charset="UTF-8">:
    • Sets the character encoding to UTF-8, allowing the document to support most characters and symbols globally.
  2. <meta name="viewport" content="width=device-width, initial-scale=1.0">:
    • Makes the webpage responsive by setting the width of the viewport to match the device's width and scaling it appropriately.
  3. <title>Music Search App</title>:
    • Sets the title of the webpage, displayed on the browser tab.
  4. Google Fonts Link:
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
    • Loads the "Poppins" font from Google Fonts.
    • wght@400;600 specifies the font weights (400 = normal, 600 = semi-bold).
    • display=swap ensures the font fallback is smooth if it’s not immediately available.
  5. External CSS Link:
    <link rel="stylesheet" href="styles.css">
    • Links an external CSS file named styles.css to style the webpage.

Body Section

The <body> contains the visible content of the webpage.

  1. <div class="container">:
    • A container element that groups all the content for better layout and styling.
  2. Heading (<h1>):
    <h1>Music Search App</h1>
    • Displays the main heading of the webpage.
  3. Input Field:
    <input type="text" id="search-input" placeholder="Search for songs, artists, or albums">
    • A text input field for users to type their search query.
    • id="search-input": Unique identifier for JavaScript or CSS.
    • placeholder: Displays placeholder text inside the input field.
  4. Button:
    <button id="search-button">Search</button>
    • A clickable button to trigger the search functionality.
    • id="search-button": Unique identifier for JavaScript interaction.
  5. Results Section:
    <div id="results"></div>
    • An empty <div> that will dynamically display the search results fetched by the app.

Script Section

<script src="script.js"></script>
  • Links an external JavaScript file named script.js.
  • This file will handle the app's functionality, such as fetching data from the iTunes API and displaying the results.

Step 2 (CSS Code):

Next, create a styles.css file to style the app. This will make your app look more appealing. Here’s an explanation of the CSS code:

General Styles

body {
  font-family: 'Poppins', sans-serif;
  background-color: #f0f4f8;
  margin: 0;
  padding: 0;
  color: #333;
}
  • font-family: 'Poppins', sans-serif;: Sets the font for the entire page to "Poppins" (a clean, modern sans-serif font).
  • background-color: #f0f4f8;: Gives the background a light grayish-blue color, creating a soft and clean look.
  • margin: 0; padding: 0;: Removes default margins and padding from the browser, ensuring consistent spacing.
  • color: #333;: Sets the text color to a dark gray, which is easy to read against the light background.

Container Styles

.container {
  max-width: 800px;
  margin: 50px auto;
  text-align: center;
}
  • max-width: 800px;: Limits the width of the container to 800px, making the content more readable on large screens.
  • margin: 50px auto;: Centers the container horizontally and adds 50px of margin at the top and bottom.
  • text-align: center;: Centers the text inside the container.

Heading Styles

h1 {
  color: #825CFF; 
  margin-bottom: 20px;
}
  • color: #825CFF;: Sets the heading color to a vibrant purple.
  • margin-bottom: 20px;: Adds 20px of space below the heading to separate it from other elements.

Search Input Styles

#search-input {
  font-family: 'Poppins', sans-serif;
  width: 70%;
  padding: 10px;
  border: 2px solid #825CFF;
  border-radius: 5px;
  outline: none;
  font-size: 16px;
}
  • font-family: 'Poppins', sans-serif;: Uses the same font as the rest of the page for consistency.
  • width: 70%;: Sets the input field width to 70% of the container's width.
  • padding: 10px;: Adds 10px of padding inside the input field, making it easier to type.
  • border: 2px solid #825CFF;: Adds a purple border around the input field.
  • border-radius: 5px;: Rounds the corners of the input field for a softer appearance.
  • outline: none;: Removes the default outline when the input is focused.
  • font-size: 16px;: Sets the font size to 16px for readability.

Search Input Focus Styles

#search-input:focus {
  border-color: #6a4ccc;
  box-shadow: 0 0 5px rgba(130, 92, 255, 0.5);
}
  • border-color: #6a4ccc;: Changes the border color to a darker purple when the input field is focused.
  • box-shadow: 0 0 5px rgba(130, 92, 255, 0.5);: Adds a subtle purple glow around the input field when focused.

Search Button Styles

#search-button {
  font-family: 'Poppins', sans-serif;
  padding: 10px 20px;
  border: none;
  background-color: #825CFF;
  color: #fff;
  border-radius: 5px;
  cursor: pointer;
  font-size: 18px;
  margin-left: 10px;
}
  • font-family: 'Poppins', sans-serif;: Uses the same font as the input field and other elements.
  • padding: 10px 20px;: Adds padding inside the button to make it more clickable.
  • border: none;: Removes the default button border.
  • background-color: #825CFF;: Sets the button's background to the same vibrant purple as the heading.
  • color: #fff;: Makes the text on the button white for contrast.
  • border-radius: 5px;: Rounds the button corners for a smoother look.
  • cursor: pointer;: Changes the cursor to a pointer when hovering over the button, indicating it’s clickable.
  • font-size: 18px;: Increases the font size for readability and emphasis.
  • margin-left: 10px;: Adds 10px of space between the input field and the button.

Search Button Hover Styles

#search-button:hover {
  background-color: #6a4ccc;
}
  • background-color: #6a4ccc;: Changes the button’s background color to a darker purple when hovered, giving it a visual effect to show interactivity.

Results Section Styles

#results {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: center;
}
  • margin-top: 20px;: Adds 20px of space above the results section.
  • display: flex;: Uses flexbox to arrange the results in a flexible layout.
  • flex-wrap: wrap;: Allows the results to wrap to the next line if there isn’t enough space.
  • gap: 20px;: Adds a 20px gap between each result card.
  • justify-content: center;: Centers the result cards horizontally within the section.

Song Card Styles

.song {
  width: 200px;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  text-align: center;
  transition: transform 0.3s, box-shadow 0.3s;
}
  • width: 200px;: Sets a fixed width for each song card.
  • padding: 15px;: Adds padding inside the card for spacing.
  • border: 1px solid #ddd;: Adds a light gray border around the card.
  • border-radius: 10px;: Rounds the corners of the card for a softer appearance.
  • background-color: #fff;: Sets the background of the card to white.
  • box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);: Adds a subtle shadow for depth.
  • text-align: center;: Centers the text inside the card.
  • transition: transform 0.3s, box-shadow 0.3s;: Adds smooth transition effects for changes in position and shadow.

Song Card Hover Styles

.song:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}
  • transform: translateY(-5px);: Moves the card slightly upwards when hovered, creating a lift effect.
  • box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);: Increases the shadow to make the card appear more elevated when hovered.

Song Image Styles

.song img {
  width: 100%;
  border-radius: 10px;
  margin-bottom: 10px;
}
  • width: 100%;: Makes the image fill the entire width of the card.
  • border-radius: 10px;: Rounds the corners of the image for a consistent look with the card.
  • margin-bottom: 10px;: Adds space below the image to separate it from the text.

Song Title and Description Styles

.song h3 {
  font-size: 16px;
  margin: 10px 0 5px;
  color: #333;
}

.song p {
  font-size: 14px;
  color: #555;
}

.song p strong {
  color: #825CFF;
}
  • h3: Sets the title of the song to a readable size with space above and below it.
  • p: Styles the description text with a smaller font size and a lighter gray color.
  • strong: Colors the strong text (like price or emphasis) in purple for contrast.

Audio Preview Styles

.audio-preview {
  margin-top: 10px;
  width: 100%;
  outline: none;
}
  • margin-top: 10px;: Adds space above the audio player.
  • width: 100%;: Makes the audio player span the entire width of the container.
  • outline: none;: Removes the outline that typically appears around the audio player.
body {
  font-family: 'Poppins', sans-serif;
  background-color: #f0f4f8;
  margin: 0;
  padding: 0;
  color: #333;
}

.container {
  max-width: 800px;
  margin: 50px auto;
  text-align: center;
}

h1 {
  color: #825CFF; 
  margin-bottom: 20px;
}

#search-input {
  font-family: 'Poppins', sans-serif;
  width: 70%;
  padding: 10px;
  border: 2px solid #825CFF; 
  border-radius: 5px;
  outline: none;
  font-size: 16px;
}

#search-input:focus {
  border-color: #6a4ccc; 
  box-shadow: 0 0 5px rgba(130, 92, 255, 0.5);
}

#search-button {
  font-family: 'Poppins', sans-serif;
  padding: 10px 20px;
  border: none;
  background-color: #825CFF; 
  color: #fff;
  border-radius: 5px;
  cursor: pointer;
  font-size: 18px;
  margin-left: 10px;
}

#search-button:hover {
  background-color: #6a4ccc;
}

#results {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: center;
}

.song {
  width: 200px;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  text-align: center;
  transition: transform 0.3s, box-shadow 0.3s;
}

.song:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.song img {
  width: 100%;
  border-radius: 10px;
  margin-bottom: 10px;
}

.song h3 {
  font-size: 16px;
  margin: 10px 0 5px;
  color: #333;
}

.song p {
  font-size: 14px;
  color: #555;
}

.song p strong {
  color: #825CFF; 
}

.audio-preview {
  margin-top: 10px;
  width: 100%;
  outline: none;
} 

Step 3 (JavaScript Code):

Now, let's add the functionality using JavaScript. Here's a breakdown of how it works:

  1. Variables and DOM Elements:
    • searchButton: Selects the button with the ID 'search-button'.
    • searchInput: Selects the input field for the search term with the ID 'search-input'.
    • resultsDiv: Selects the div element where search results will be displayed.
  2. fetchMusic Function:
    • This is an asynchronous function that fetches data from the iTunes API using the fetch method.
    • The API URL is constructed with the search query from the input field, encoded to handle special characters.
    • The function makes a GET request to the iTunes API endpoint that searches for songs based on the query.
    • If the fetch request is successful, the response is parsed as JSON, and the displayResults function is called to display the songs.
    • If there is an error (e.g., network issues), an error message is shown on the page.
  3. displayResults Function:
    • This function takes the songs array returned by the API and dynamically generates HTML to display each song's details.
    • If no songs are found, it displays a message saying "No results found."
    • For each song in the songs array:
      • A div element with the class 'song' is created.
      • The song's image, title, artist name, price, and a preview audio player are added to the song's div.
      • The song's price is formatted, and if it's not available, it shows "Price not available."
      • The songDiv is appended to the resultsDiv to display the song on the page.
  4. Event Listeners:
    • The searchButton listens for a click event. When the button is clicked:
      • The value of the search input is retrieved and trimmed of any extra spaces.
      • If the search input is not empty, the fetchMusic function is called with the query.
      • If the input is empty, it displays a message asking the user to enter a search term.
    • The searchInput listens for a "keypress" event, and if the "Enter" key is pressed, it triggers a click event on the searchButton, effectively performing the search.
const searchButton = document.getElementById('search-button');
const searchInput = document.getElementById('search-input');
const resultsDiv = document.getElementById('results');

async function fetchMusic(query) {
  const API_URL = `https://itunes.apple.com/search?term=${encodeURIComponent(query)}&entity=song&limit=20`;
  try {
    const response = await fetch(API_URL);
    const data = await response.json();
    displayResults(data.results);
  } catch (error) {
    console.error('Error fetching music:', error);
    resultsDiv.innerHTML = `<p>Error fetching results. Please try again later.</p>`;
  }
}

function displayResults(songs) {
  resultsDiv.innerHTML = '';
  if (songs.length === 0) {
    resultsDiv.innerHTML = '<p>No results found.</p>';
    return;
  }

  songs.forEach(song => {
    const songDiv = document.createElement('div');
    songDiv.classList.add('song');

    const price = song.trackPrice
      ? `$${song.trackPrice.toFixed(2)}`
      : "Price not available";

    songDiv.innerHTML = `
      <img src="${song.artworkUrl100}" alt="${song.trackName}">
      <h3>${song.trackName}</h3>
      <p>${song.artistName}</p>
      <p><strong>Price:</strong> ${price}</p>
      <audio class="audio-preview" controls>
        <source src="${song.previewUrl}" type="audio/mpeg">
        Your browser does not support the audio element.
      </audio>
    `;

    resultsDiv.appendChild(songDiv);
  });
}

searchButton.addEventListener('click', () => {
  const query = searchInput.value.trim();
  if (query) {
    fetchMusic(query);
  } else {
    resultsDiv.innerHTML = '<p>Please enter a search term.</p>';
  }
});

searchInput.addEventListener('keypress', (event) => {
  if (event.key === 'Enter') {
    searchButton.click();
  }
});

Final Output:

create-a-music-search-app-using-html-css-and-javascript.gif

Conclusion:

Building a Music Search App using HTML, CSS, and JavaScript with iTunes integration provides a great opportunity to practice front-end development. By fetching music data from iTunes, the app allows users to search for songs, artists, and albums, displaying relevant information such as song names, artists, prices, and audio previews.

This simple yet functional app can be enhanced further by adding additional features like filtering results, sorting, or even integrating more music sources. By experimenting with these improvements, you can gain valuable experience in working with APIs and building interactive web applications.

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

Please allow ads on our site🥺