Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/ClaytonSeager/InifinityScroll/llms.txt

Use this file to discover all available pages before exploring further.

Infinity Scroll includes a built-in keyword search that queries the Unsplash search API. When a search is submitted, the existing gallery is cleared and replaced with results matching the term. Infinite scroll then continues to load additional matching results as the user scrolls β€” the search context is preserved until explicitly cleared. The search UI is a pill-shaped bar containing a plain text input and a button:
<div class="search-container">
    <div class="search-bar">
        <input type="text" id="search-input" placeholder="Search images...">
        <button id="search-button">
            <span class="search-icon">πŸ”</span>
        </button>
    </div>
</div>
There are two ways to trigger a search:
  • Click the πŸ” button β€” fires the click event on #search-button
  • Press Enter β€” the keypress listener on #search-input detects e.key === 'Enter'
Both paths call the same handleSearch() function:
searchButton.addEventListener('click', handleSearch);
searchInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
        handleSearch();
    }
});

What handleSearch() does

const handleSearch = () => {
    query = searchInput.value;       // Capture the current input text as the active query
    imageContainer.innerHTML = '';   // Clear all existing images from the gallery
    totalLoadedImages = 0;           // Reset the running image count to zero
    imageCounter.textContent = '0';  // Update the on-screen counter to reflect the reset
    loader.hidden = false;           // Show the loading overlay immediately
    getPhotos();                     // Kick off a fetch with the new query
};
LinePurpose
query = searchInput.valueStores the search term in the module-level query variable, which getApiUrl() reads to choose the correct API endpoint
imageContainer.innerHTML = ''Wipes the #Image__Container DOM node so the new results start from a clean slate
totalLoadedImages = 0Resets the running total so the counter reflects only the current search’s results
imageCounter.textContent = '0'Immediately syncs the visible counter badge to the reset value
loader.hidden = falseMakes the full-screen loading overlay visible before the fetch begins
getPhotos()Initiates the API call; getApiUrl() will now build a search URL because query is non-empty

How search affects the API URL

The getApiUrl() function inspects query to choose between the Unsplash random-photos endpoint and the search endpoint:
const getApiUrl = () => {
    const baseUrl = 'https://api.unsplash.com/photos/';
    const searchUrl = 'https://api.unsplash.com/search/photos/';
    const params = `client_id=${KEY}&count=${count}`;
    
    return query 
        ? `${searchUrl}?query=${query}&${params}`
        : `${baseUrl}random/?${params}`;
};
StateURL usedExample
query is a non-empty stringhttps://api.unsplash.com/search/photos/?query=<term>&client_id=<KEY>&count=<count>…?query=mountains&client_id=…&count=10
query is '' (empty string)https://api.unsplash.com/photos/random/?client_id=<KEY>&count=<count>…/random/?client_id=…&count=10

Search results parsing

The two Unsplash endpoints return data in different shapes. The random endpoint returns a top-level array, while the search endpoint wraps results inside a results property. A single ternary in getPhotos() normalises both:
const getPhotos = async () => {
    try {
        const response = await fetch(getApiUrl());
        const data = await response.json();
        
        photosArray = query ? data.results : data;
        
        displayPhotos();
    } catch (error) {
        console.error('Error fetching photos:', error);
    }
}
  • Search response (query is set): data.results β€” an array of photo objects nested inside the search response wrapper.
  • Random response (query is ''): data β€” the response body is itself the array of photo objects.
After this line, photosArray always holds a plain array of photo objects regardless of which endpoint was called, so displayPhotos() can iterate it without any further branching. To return to the random photo feed, the user empties the search input and submits (either by clicking the button or pressing Enter). When searchInput.value is an empty string, handleSearch() sets query = ''. getApiUrl() then evaluates query as falsy and returns the random endpoint URL β€” random photos resume from the next fetch onward.
This implementation does not use cursor-based pagination for search results. Each scroll event beyond the threshold triggers a fresh call to the search endpoint with the same query term, returning a new set of up to count matching images. The Unsplash API may return a different selection of results on each call.

Build docs developers (and LLMs) love