11const searchText = document . getElementById ( "search-input" ) ;
22const searchBtn = document . getElementById ( "search-btn" ) ;
33const imageCards = document . getElementById ( "image-cards" ) ;
4+ const searchResultDiv = document . getElementById ( "search-resultDiv" ) ;
45const imageApi = "https://api.unsplash.com/search/photos?query=" ;
56const accessKey = "cZkBLec2VWlXBAgs785p7uw9nagFu_G0Zgb8e5lK400" ;
6- const fetchImages = async ( query ) => {
7+ let currentPage = 1 ;
8+ let total_pages = "" ;
9+
10+
11+ const fetchImages = async ( query , page = 1 ) => {
712 if ( ! query ) {
813 console . log ( "Query is empty" ) ;
14+
915 return ;
1016 }
1117 try {
12- const response = await fetch ( `${ imageApi } ${ query } &client_id=${ accessKey } ` ) ;
18+ const response = await fetch ( `${ imageApi } ${ query } &client_id=${ accessKey } &page= ${ page } ` ) ;
1319 const data = await response . json ( ) ;
20+ total_pages = data . total_pages ;
1421 console . log ( data ) ;
22+
23+ console . log ( data . total_pages ) ;
24+ console . log ( total_pages ) ;
1525
1626 displayImages ( data . results ) ;
1727 } catch ( error ) {
@@ -20,25 +30,54 @@ const fetchImages = async (query) => {
2030} ;
2131
2232const displayImages = ( images ) => {
23- imageCards . innerHTML = "" ;
33+ if ( currentPage === 1 ) {
34+ imageCards . innerHTML = "" ;
35+
36+ }
2437 images . forEach ( ( image ) => {
2538 const imageBlock = document . createElement ( "div" ) ;
2639 const imgElement = document . createElement ( "img" ) ;
2740 const imgCaption = document . createElement ( "p" ) ;
28- imgCaption . innerText = image . description ;
41+
42+ imgCaption . innerText = image . description || "no description available" ;
2943 imgElement . src = image . urls . small ;
30- imgElement . alt = image . alt_description ;
44+ imgElement . alt = image . alt_description || "Image" ;
45+
3146 imageBlock . className = "image-card" ;
3247 imageBlock . appendChild ( imgElement ) ;
3348 imageBlock . appendChild ( imgCaption ) ;
34-
3549 imageCards . appendChild ( imageBlock ) ;
3650 } ) ;
51+ if ( currentPage < total_pages ) {
52+ const moreButton = document . createElement ( "button" ) ;
53+ moreButton . innerText = "More" ;
54+ moreButton . id = "more-button" ;
55+ searchResultDiv . appendChild ( moreButton ) ;
56+ }
57+
58+ moreButton . addEventListener ( "click" , searchMoreImage ) ;
59+
60+
3761} ;
3862
3963const searchImage = ( ) => {
4064 const query = searchText . value . trim ( ) ;
4165 fetchImages ( query ) ;
4266} ;
4367
68+ const searchMoreImage = ( ) => {
69+ const query = searchText . value . trim ( ) ;
70+ if ( currentPage < total_pages ) {
71+ currentPage ++ ;
72+ fetchImages ( query , currentPage )
73+ }
74+
75+ }
76+
4477searchBtn . addEventListener ( "click" , searchImage ) ;
78+
79+ searchText . addEventListener ( "keydown" , ( e ) => {
80+ if ( e . key === "Enter" ) {
81+ searchImage ( ) ;
82+ }
83+ } )
0 commit comments