-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
38 lines (33 loc) · 1.54 KB
/
script.js
File metadata and controls
38 lines (33 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const searchBtn = document.getElementById("searchBtn");
const searchInput = document.getElementById("searchInput");
const resultsDiv = document.getElementById("results");
searchBtn.addEventListener("click", () => {
const query = searchInput.value.trim();
if (query !== "") {
fetchBooks(query);
}
});
async function fetchBooks(query) {
resultsDiv.innerHTML = "<p>Loading...</p>";
try {
const res = await fetch(`https://openlibrary.org/search.json?q=${query}`);
const data = await res.json();
if (data.docs.length === 0) {
resultsDiv.innerHTML = "<p>No results found.</p>";
return;
}
resultsDiv.innerHTML = data.docs.slice(0, 20).map(book => {
const title = book.title || "No Title";
const author = book.author_name ? book.author_name.join(", ") : "Unknown Author";
const year = book.first_publish_year || "N/A";
const coverId = book.cover_i;
const coverUrl = coverId ? `https://covers.openlibrary.org/b/id/${coverId}-M.jpg` : "https://via.placeholder.com/200x280?text=No+Cover";
return `<div class="card"><img src="${coverUrl}" alt="${title}">
<h3>${title}</h3><p><strong>Author:</strong> ${author}</p><p><strong>Year:</strong> ${year}</p>
<a href="https://openlibrary.org${book.key}" target="_blank">View More</a></div>`;
}).join("");
} catch (error) {
resultsDiv.innerHTML = "<p>Error fetching data. Please try again.</p>";
console.error(error);
}
}