%%html
<style>
body {
font-family: arial, sans-serif;
}
.results {
margin-top: 20px;
}
.result-item {
border: 1px solid #ccc;
padding: 10px;
margin-bottom: 10px;
}
</style>
<h1>search itunes</h1>
<input
type="text"
id="search-input"
placeholder="enter artist, album, or song"
/>
<button id="search-button">search</button>
<div class="results" id="results"></div>
<script>
document
.getElementById("search-button")
.addEventListener("click", function () {
const searchTerm = document.getElementById("search-input").value;
const apiUrl = `https://itunes.apple.com/search?term=${encodeURIComponent(
searchTerm
)}&media=music&limit=10`;
fetch(apiUrl)
.then((response) => response.json())
.then((data) => {
const resultsDiv = document.getElementById("results");
resultsDiv.innerHTML = "";
if (data.resultCount === 0) {
resultsDiv.innerHTML = "<p>oops! no results found. try again!</p>";
return;
}
data.results.forEach((item) => {
const resultItem = document.createElement("div");
resultItem.className = "result-item";
resultItem.innerHTML = `
<h3>${item.trackName} by ${item.artistName}</h3>
<p><strong>album:</strong> ${item.collectionName}</p>
<p><strong>price:</strong> $${item.collectionPrice}</p>
<a href="${item.trackViewUrl}" target="_blank">view on itunes</a>
<img src="${item.artworkUrl100}" alt="${item.trackName} artwork" />
`;
resultsDiv.appendChild(resultItem);
});
})
.catch((error) => {
console.error("error fetching data:", error);
document.getElementById("results").innerHTML =
"<p>uh oh! something went wrong. did you break the internet?</p>";
});
});
</script>
search itunes