-
Notifications
You must be signed in to change notification settings - Fork 1
/
script.js
61 lines (54 loc) · 2.1 KB
/
script.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const placeHolderMessage = document.querySelector(".place-holder-message");
const searchForm = document.getElementById("search-form");
const booksDisplay = document.getElementById("books-display");
const defaultBookImage = "./img/book.png";
const googleBooksURL = "https://www.googleapis.com/books/v1/volumes?q=";
let apiKey = "&key=AIzaSyCw6aeDwd2srAlaiVBFSSBvyl2O7atCTaA";
searchForm.addEventListener("submit", () => {
placeHolderMessage.style.display = "none";
let searchInput = document.getElementById("search-input").value;
let searchQuery = `${googleBooksURL}${searchInput}${apiKey}`;
getBooks(searchQuery);
});
async function getBooks(query) {
const booksPromise = await fetch(query);
const booksData = await booksPromise.json();
if (booksData.items) {
displayBooks(booksData.items);
} else {
booksDisplay.innerHTML = "";
placeHolderMessage.style.display = "block";
placeHolderMessage.innerHTML = "Sorry no results!";
}
}
function displayBooks(books) {
booksDisplay.innerHTML = "";
books.forEach((book) => {
let volumeInfo = book.volumeInfo;
let bookImage = volumeInfo.imageLinks;
let title = volumeInfo.title || "N/A";
let authors = volumeInfo.authors || "N/A";
let previewLink = volumeInfo.previewLink || "N/A";
let publishdate = volumeInfo.publishedDate || "N/A";
let publisher = volumeInfo.publisher || "N/A";
let smallThumbnail =
bookImage && bookImage.smallThumbnail
? bookImage.smallThumbnail
: defaultBookImage;
let div = document.createElement("div");
div.innerHTML = `
<h3> ${title} </h3>
<div class= "book-img">
<img src= "${smallThumbnail}" alt= "Image book cover ">
</div>
<div class = "book-details">
<small> <strong>Author(s)</strong>: ${authors}</small>
<small> <strong>Publishers</strong>: ${publisher}</small>
<small> <strong>Published</strong>: ${publishdate}</small>
</div>
<a href = "${previewLink}" class ="book-link" target="_blank"> Google Books Preview </a>
`;
div.classList.add("book-styling");
booksDisplay.append(div);
});
}