index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. var apiUrl = 'https://www.googleapis.com/books/v1';
  2. var allBooks = [];
  3. var $booksList = $('#books-list'),
  4. $bookInfo = $('#book-info'),
  5. $formSearch = $('#form-search');
  6. $formSearch.on('submit', function(event) {
  7. event.preventDefault();
  8. var queryString = $('[name=query]', this).val();
  9. getBook(queryString);
  10. });
  11. function getBook(query = '') {
  12. $.ajax({
  13. url: `${apiUrl}/volumes?q=${query}`,
  14. method: 'GET'
  15. })
  16. .done(response => {
  17. allBooks = response.items;
  18. $booksList.parents('.panel').show();
  19. allBooks.forEach(book => {
  20. $('<a>')
  21. .addClass('list-group-item')
  22. .attr('href', '')
  23. .text(book.volumeInfo.title)
  24. .appendTo($booksList)
  25. .attr('data-id', book.id)
  26. .on('click', function(event) {
  27. event.preventDefault();
  28. var id = $(this).data('id');
  29. var book = allBooks.find(item => item.id === id);
  30. $bookInfo.empty().hide().fadeIn();
  31. $('<div>')
  32. .addClass('panel-heading')
  33. .text( `${book.volumeInfo.title} | ${book.volumeInfo.authors.join(', ')} (${book.volumeInfo.publishedDate})` )
  34. .appendTo($bookInfo);
  35. $('<div>')
  36. .addClass('panel-body')
  37. .appendTo($bookInfo)
  38. .html(`
  39. <img src="${book.volumeInfo.imageLinks.thumbnail}" alt="${book.volumeInfo.title}" class="pull-left">
  40. <p>${book.volumeInfo.description}</p>
  41. <a href="${book.volumeInfo.previewLink}" target="_blank">Readmore...</a>
  42. `)
  43. })
  44. });
  45. })
  46. .fail(error => {
  47. console.log('error', error);
  48. });
  49. }