### Install Infinite Scroll via CDN (HTML) Source: https://github.com/metafizzy/infinite-scroll/blob/master/README.md This snippet shows how to include the Infinite Scroll library in an HTML document using a CDN link from unpkg. It offers both minified and un-minified versions. ```html ``` -------------------------------- ### Development Commands (Shell) Source: https://github.com/metafizzy/infinite-scroll/blob/master/README.md This snippet lists development commands for the Infinite Scroll project, including installing dependencies, linting the code, and running tests. It assumes Node.js v14 and npm v6 are installed, with nvm recommended for version management. ```shell nvm use npm install npm run lint npm test ``` -------------------------------- ### Install and Include Infinite Scroll via CDN or Package Managers Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Infinite Scroll can be included in projects using CDN links, npm, or Yarn. After inclusion, it can be initialized as a global `InfiniteScroll` object. ```html ``` -------------------------------- ### Install and Include Infinite Scroll via npm or Yarn Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Infinite Scroll can be installed using npm or Yarn. It can then be imported and used in CommonJS or ES module environments. ```bash # npm installation npm install infinite-scroll # Yarn installation yarn add infinite-scroll ``` ```javascript // CommonJS/Node.js const InfiniteScroll = require('infinite-scroll'); let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post' }); // ES modules import InfiniteScroll from 'infinite-scroll'; let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post' }); ``` -------------------------------- ### Initialize Infinite Scroll with Element Scrolling (JavaScript) Source: https://github.com/metafizzy/infinite-scroll/blob/master/sandbox/element-scroll.html This snippet initializes the Infinite Scroll library to use a specific DOM element (`.posts-container`) as the scrollable area. It appends new posts from `.post` elements and uses `.pagination__next` to find the next page link. The `elementScroll: true` option is key for this functionality. ```javascript var postsContainer = document.querySelector('.posts-container'); var infScroll = new InfiniteScroll( postsContainer, { elementScroll: true, append: '.post', path: '.pagination__next', // history: false, }); ``` -------------------------------- ### Custom Fetch Request Settings with Infinite Scroll Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Configure Infinite Scroll to use custom settings for its Fetch API requests. This allows for advanced options such as setting request methods (GET, POST), custom headers (like authorization tokens), handling credentials, and managing CORS policies. You can provide static options or a function that dynamically generates options per request. ```javascript // Static fetch options let infScroll = new InfiniteScroll('.container', { path: '/api/posts/page/{{#}}', append: '.post', responseBody: 'json', fetchOptions: { method: 'GET', headers: { 'Authorization': 'Bearer ' + authToken, 'Content-Type': 'application/json' }, credentials: 'include', mode: 'cors' } }); // Dynamic fetch options function let infScroll = new InfiniteScroll('.container', { path: '/api/posts', append: '.post', responseBody: 'json', path: function() { return '/api/posts'; }, fetchOptions: function() { // Regenerate options for each request return { method: 'POST', headers: { 'Authorization': 'Bearer ' + getToken(), 'Content-Type': 'application/json' }, body: JSON.stringify({ page: this.pageIndex + 1, limit: 20, filters: getCurrentFilters() }) }; } }); ``` -------------------------------- ### Infinite Scroll with Load More Button (JavaScript) Source: https://github.com/metafizzy/infinite-scroll/blob/master/sandbox/scroll-3.html This JavaScript code snippet configures the Infinite Scroll library to load content automatically for the first three pages. After the third page is loaded, it displays a 'load-more-button', disables further scroll-based loading, and switches to manual loading via the button click. This is useful for controlling the initial user experience and providing a clear way to load more content. ```javascript var container = document.querySelector('.posts-container'); var infScroll = new InfiniteScroll( container, { path: '.pagination__next', append: '.post', historyTitle: true, history: false, }); var loadMoreButton = document.querySelector('.load-more-button'); var loadPageCount = 0; infScroll.on( 'load', onPageLoad ); function onPageLoad() { if ( infScroll.loadCount == 3 ) { loadMoreButton.style.display = 'inline-block'; infScroll.options.loadOnScroll = false; infScroll.off( 'load', onPageLoad ); } } loadMoreButton.onclick = function() { infScroll.loadNextPage(); }; ``` -------------------------------- ### Infinite Scroll Button Integration Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Configures Infinite Scroll to use a specified button element for loading more pages. When the button is clicked, it triggers the loading of the next page. The button is automatically disabled during a request, re-enabled upon successful load, and hidden when the last page is reached or an error occurs. This setup disables automatic scroll loading. ```html
...
Loading...
No more pages
Error loading page
``` ```javascript let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post', button: '.load-next-button', status: '.page-load-status', scrollThreshold: false // Disable scroll loading }); // Button automatically: // - Disables during request // - Re-enables on load // - Hides on last page or error ``` -------------------------------- ### Initialize Infinite Scroll with Prefill - JavaScript Source: https://github.com/metafizzy/infinite-scroll/blob/master/sandbox/prefill.html Initializes the Infinite Scroll library with the 'prefill' option set to true. This option ensures that content is loaded to fill the viewport initially, improving perceived loading times. It requires a container element and selectors for new posts and pagination. ```javascript var infScroll = new InfiniteScroll( '.posts-container', { path: '.pagination__next', append: '.post', prefill: true, history: false, }); ``` -------------------------------- ### Initialize Infinite Scroll Instance Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Creates an Infinite Scroll instance on a container element. It configures automatic page loading and allows for various options such as path, append selectors, history management, and callbacks. Dependencies include the Infinite Scroll library itself. It takes a selector for the container and an options object. ```javascript let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post', history: false }); ``` ```javascript let infScroll = new InfiniteScroll('.container', { path: '.pagination__next', // Selector for next page link append: '.post', // Selector for items to append checkLastPage: true, // Stop when no more pages prefill: true, // Load pages until scroll appears scrollThreshold: 400, // Distance from bottom to trigger (px) status: '.page-load-status', // Status message container button: '.load-next-button', // Manual load button history: 'replace', // Update URL ('replace' or 'push') historyTitle: true, // Update page title hideNav: '.pagination', // Hide navigation element debug: true, // Console logging onInit: function() { this.on('append', function(body, path, items) { console.log(`Loaded ${items.length} items from ${path}`); }); } }); ``` -------------------------------- ### Initialize Infinite Scroll with Load More Button (JavaScript) Source: https://github.com/metafizzy/infinite-scroll/blob/master/sandbox/button-first.html This snippet demonstrates how to initialize the Infinite Scroll library and connect it to a 'load more' button. It configures the scroll to load the next page when the button is clicked and then hides the button. Dependencies include the Infinite Scroll library. Inputs are the DOM elements for the container, next page path, and posts to append. Outputs are dynamically loaded content. ```javascript var container = document.querySelector('.posts-container'); var infScroll = new InfiniteScroll( container, { path: '.pagination__next', append: '.post', historyTitle: true, loadOnScroll: false, history: false, }); var loadMoreButton = document.querySelector('.load-more-button'); loadMoreButton.onclick = function() { infScroll.options.loadOnScroll = true; infScroll.loadNextPage(); loadMoreButton.style.display = 'none'; }; ``` -------------------------------- ### Initialize Infinite Scroll with Options (JavaScript) Source: https://github.com/metafizzy/infinite-scroll/blob/master/README.md This JavaScript snippet shows how to initialize Infinite Scroll on a container element. It includes comments explaining various configuration options such as 'path' for the next page URL, 'append' for content insertion, and 'scrollThreshold' for trigger distance. ```javascript let infScroll = new InfiniteScroll( '.container', { // defaults listed path: undefined, // REQUIRED. Determines the URL for the next page // Set to selector string to use the href of the next page's link // path: '.pagination__next' // Or set with {{#}} in place of the page number in the url // path: '/blog/page/{{#}}' // or set with function // path: function() { // return return '/articles/P' + ( ( this.loadCount + 1 ) * 10 ); // } append: undefined, // REQUIRED for appending content // Appends selected elements from loaded page to the container checkLastPage: true, // Checks if page has path selector element // Set to string if path is not set as selector string: // checkLastPage: '.pagination__next' prefill: false, // Loads and appends pages on intialization until scroll requirement is met. responseBody: 'text', // Sets the method used on the response. // Set to 'json' to load JSON. domParseResponse: true, // enables parsing response body into a DOM // disable to load flat text fetchOptions: undefined, // sets custom settings for the fetch() request // for setting headers, cors, or POST method // can be set to an object, or a function that returns an object outlayer: false, // Integrates Masonry, Isotope or Packery // Appended items will be added to the layout scrollThreshold: 400, // Sets the distance between the viewport to scroll area // for scrollThreshold event to be triggered. elementScroll: false, // Sets scroller to an element for overflow element scrolling loadOnScroll: true, // Loads next page when scroll crosses over scrollThreshold history: 'replace', // Changes the browser history and URL. // Set to 'push' to use history.pushState() // to create new history entries for each page change. historyTitle: true, // Updates the window title. Requires history enabled. hideNav: undefined, // Hides navigation element status: undefined, // Displays status elements indicating state of page loading: // .infinite-scroll-request, .infinite-scroll-load, .infinite-scroll-error // status: '.page-load-status' button: undefined, // Enables a button to load pages on click // button: '.load-next-button' onInit: undefined, // called on initialization // useful for binding events on init // onInit: function() { // this.on( 'append', function() {...}) // } debug: false, // Logs events and state changes to the console. }) ``` -------------------------------- ### Initialize Infinite Scroll with Button Loading Source: https://github.com/metafizzy/infinite-scroll/blob/master/sandbox/button-load.html This snippet demonstrates how to initialize the Infinite Scroll library using a 'load more' button. It specifies the container, the selector for the next page path, the selector for appending new posts, and the selector for the button that triggers loading more content. It also disables scroll-based loading and history management. ```javascript var container = document.querySelector('.posts-container'); var infScroll = new InfiniteScroll( container, { path: '.pagination__next', append: '.post', button: '.load-more-button', loadOnScroll: false, history: false, }); ``` -------------------------------- ### Integrate Layout Libraries with Infinite Scroll Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Integrate Infinite Scroll with layout libraries like Masonry, Isotope, or Packery to manage appended items in dynamic and responsive grid layouts. This requires initializing the layout library first and then passing its instance to Infinite Scroll. The `imagesLoaded` library is recommended for proper timing of layout updates. ```javascript // Initialize layout library first let msnry = new Masonry('.grid', { itemSelector: '.grid-item', columnWidth: 200 }); // Pass layout instance to Infinite Scroll let infScroll = new InfiniteScroll('.grid', { path: '/photos/page/{{#}}', append: '.grid-item', outlayer: msnry, prefill: true }); // Requires imagesLoaded library for proper layout timing // Appended items automatically added to layout after images load // With Isotope let iso = new Isotope('.grid', { itemSelector: '.grid-item', layoutMode: 'fitRows' }); let infScroll = new InfiniteScroll('.grid', { path: '/items/page/{{#}}', append: '.grid-item', outlayer: iso }); ``` -------------------------------- ### Initialize Infinite Scroll JavaScript Source: https://github.com/metafizzy/infinite-scroll/blob/master/sandbox/button-class.html This JavaScript code initializes the Infinite Scroll library. It targets a container element for posts and specifies selectors for the next page path, post elements, load more button, and status display. It also configures options like historyTitle, scrollThreshold, and debug mode. Dependencies include the Infinite Scroll library. ```javascript var container = document.querySelector('.posts-container'); var infScroll = new InfiniteScroll( container, { path: '.pagination__next', append: '.post', historyTitle: true, scrollThreshold: false, history: false, button: '.load-more-button', status: '.scroll-status', debug: true }); ``` -------------------------------- ### Basic HTML Structure for Infinite Scroll Source: https://github.com/metafizzy/infinite-scroll/blob/master/README.md This HTML structure demonstrates the required container and item elements for Infinite Scroll to function. The '.container' element will hold the content, and '.post' elements represent individual items that will be loaded. ```html
...
...
...
...
``` -------------------------------- ### Initialize Infinite Scroll JavaScript Source: https://github.com/metafizzy/infinite-scroll/blob/master/sandbox/container-scroll.html This JavaScript snippet demonstrates how to initialize the Infinite Scroll library. It targets a specific container element and configures various options for infinite scrolling behavior, such as the scrolling element, content appending, and pagination path. ```javascript var postsContainer = document.querySelector('.posts-container'); var infScroll = new InfiniteScroll( postsContainer, { elementScroll: '.sidebar', append: '.post', path: '.pagination\__next', scrollThreshold: 200, // history: false, }); ``` -------------------------------- ### Initialize Infinite Scroll with jQuery Source: https://github.com/metafizzy/infinite-scroll/blob/master/sandbox/jquery-plugin.html This snippet demonstrates how to initialize the Infinite Scroll plugin using jQuery. It selects a container element and configures the plugin with options for the pagination path, the element to append, and a status element. ```javascript var $postsContainer = $('.posts-container').infiniteScroll({ path: '.pagination__next', append: '.post', status: '.scroll-status' }); ``` -------------------------------- ### Triggering jQuery and Vanilla JS Events with Isotope Source: https://github.com/metafizzy/infinite-scroll/blob/master/sandbox/page/6.html Demonstrates how to bind to events in Isotope using standard jQuery event methods. This replaces older plugin method syntax and is applicable to Isotope versions 2.2.1 and later. It simplifies event handling by leveraging familiar jQuery patterns. ```javascript // previous plugin method syntax // Isotope <= v2.2.0 // $grid.isotope( 'on', 'layoutComplete', function() {...}) // standard jQuery event // Isotope >= v2.2.1 $grid.on( 'layoutComplete', function() {...}) ``` -------------------------------- ### Prefill Content Until Scroll Appears with Infinite Scroll Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Automatically load pages until the content container is tall enough to necessitate scrolling. This option is beneficial for ensuring content is immediately visible without user interaction, especially with variable content heights. Loading stops when the scrollbar appears, the last page is reached, or an error occurs. ```javascript let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post', prefill: true // Keep loading until scroll is needed }); // Useful for variable content heights let infScroll = new InfiniteScroll('.gallery', { path: '/photos/page/{{#}}', append: '.photo', prefill: true, outlayer: masonryInstance // Works with layout libraries }); ``` -------------------------------- ### Manually Load Next Page with loadNextPage() Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Programmatically loads the next page, which is particularly useful when using button mode or custom scroll logic. This method can be called on demand to fetch additional content. It returns a promise that resolves with loaded items or rejects on error. The `canLoad` property indicates if more pages are available. ```javascript let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post', loadOnScroll: false // Disable automatic scroll loading }); // Load page on custom trigger document.querySelector('.load-more-btn').addEventListener('click', function() { infScroll.loadNextPage(); }); // Conditional loading with promise async function loadIfLoggedIn() { if (user.isAuthenticated) { try { let result = await infScroll.loadNextPage(); console.log('Loaded items:', result.items); } catch (error) { console.error('Load failed:', error); } } } // Load multiple pages programmatically function loadPages(count) { let loaded = 0; infScroll.on('append', function onAppend() { loaded++; if (loaded < count && infScroll.canLoad) { infScroll.loadNextPage(); } else { infScroll.off('append', onAppend); } }); infScroll.loadNextPage(); } ``` -------------------------------- ### Masonry Layout CSS Styling Source: https://github.com/metafizzy/infinite-scroll/blob/master/sandbox/unsplash-masonry.html Provides CSS rules for creating a masonry layout, including basic styling for the grid container and individual items. It sets up responsive column widths and ensures images display correctly within their containers. ```css html { overflow-y: scroll; } body { padding-bottom: 400px; } .grid-sizer, .grid-item { width: 25%; } .grid-item img { display: block; max-width: 100%; } .grid-item__caption { position: absolute; left: 0; bottom: 0; font-size: 14px; } .grid-item__caption a { color: white; padding: 0 10px; text-decoration: none; } ``` -------------------------------- ### Retrieve Infinite Scroll Instance with data() Method Source: https://context7.com/metafizzy/infinite-scroll/llms.txt The InfiniteScroll.data() static method retrieves the Infinite Scroll instance associated with a DOM element or a selector. It returns the instance if found, or undefined otherwise. This allows direct access to instance properties and methods. ```javascript let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post' }); let container = document.querySelector('.container'); let instance = InfiniteScroll.data(container); let instance = InfiniteScroll.data('.container'); if (instance) { console.log('Current page:', instance.pageIndex); console.log('Load count:', instance.loadCount); console.log('Can load more:', instance.canLoad); instance.loadNextPage(); } let noInstance = InfiniteScroll.data('.non-existent'); console.log(noInstance); // undefined ``` -------------------------------- ### Listen to Infinite Scroll Lifecycle Events Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Subscribe to various events throughout the infinite scroll lifecycle to implement custom behaviors and UI updates. These events include request initiation, successful loading, item appending, reaching the last page, errors, history updates, and scroll threshold crossing. The library handles DOM manipulation and fetching, allowing customization at different stages. ```javascript let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post' }); // request: Fetch started infScroll.on('request', function(path, fetchPromise) { console.log('Loading:', path); // Show custom loading indicator document.querySelector('.custom-loader').style.display = 'block'; }); // load: Page fetched successfully infScroll.on('load', function(body, path, response) { console.log('Loaded:', path, 'Title:', body.title); // body is parsed HTML document or JSON depending on responseBody option }); // append: Items added to DOM infScroll.on('append', function(body, path, items, response) { console.log(`Appended ${items.length} items from ${path}`); // Initialize components on new items items.forEach(item => { // Apply animations, attach event handlers, etc. item.classList.add('fade-in'); }); }); // last: Reached final page infScroll.on('last', function(body, path) { console.log('No more pages'); document.querySelector('.end-message').style.display = 'block'; }); // error: Request failed infScroll.on('error', function(error, path, response) { console.error('Load error:', error, 'Path:', path); document.querySelector('.error-message').textContent = 'Failed to load content. Please try again.'; }); // history: URL updated infScroll.on('history', function(title, path) { console.log('URL changed to:', path); // Track page views in analytics gtag('config', 'GA_MEASUREMENT_ID', { page_path: path }); }); // scrollThreshold: Scroll position crossed threshold infScroll.on('scrollThreshold', function() { console.log('Threshold reached'); }); ``` -------------------------------- ### Infinite Scroll Status Indicators Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Implements visual loading indicators using the 'status' option. This option takes a selector for a container element that holds specific child divs for different states: '.infinite-scroll-request' for loading, '.infinite-scroll-last' for the end of content, and '.infinite-scroll-error' for loading failures. These elements are automatically shown or hidden based on the current state of the infinite scroll instance. ```html
...

Loading more posts...

End of content

Could not load page. Try again

``` ```javascript let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post', status: '.page-status' }); // Status container shows/hides automatically // Individual child elements display based on state: // .infinite-scroll-request - shown during fetch // .infinite-scroll-error - shown on error // .infinite-scroll-last - shown when no more pages ``` -------------------------------- ### Use Infinite Scroll as a jQuery Plugin Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Infinite Scroll can be used as a jQuery plugin, offering a familiar syntax for initialization, event handling, and destruction. It also allows accessing the instance via jQuery's data method. ```javascript $('.container').infiniteScroll({ path: '/blog/page/{{#}}', append: '.post', history: false }); $('.container').on('append.infiniteScroll', function(event, body, path, items) { console.log(`Loaded ${items.length} items`); }); $('.container').on('last.infiniteScroll', function() { console.log('Last page reached'); }); let infScroll = $('.container').data('infiniteScroll'); infScroll.loadNextPage(); $('.container').infiniteScroll('destroy'); let instance = InfiniteScroll.data('.container'); ``` -------------------------------- ### Define Next Page URL Path Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Specifies how Infinite Scroll determines the URL for the next page of content. This can be done using a CSS selector for a link, a template string with a page number placeholder, or a dynamic function for more complex URL generation. It requires the `path` option to be set. ```javascript let infScroll = new InfiniteScroll('.container', { path: '.pagination__next', append: '.post' }); ``` ```javascript let infScroll = new InfiniteScroll('.container', { path: '/articles/page/{{#}}', append: '.post' }); ``` ```javascript let infScroll = new InfiniteScroll('.container', { path: function() { // this.loadCount = number of pages loaded (starts at 0) // this.pageIndex = current page number let pageNumber = this.pageIndex + 1; if (pageNumber > 10) return false; // Stop loading after page 10 return `/api/posts?page=${pageNumber}&limit=20`; }, append: '.post' }); ``` ```javascript let infScroll = new InfiniteScroll('.container', { path: '?page={{#}}', append: '.post' }); ``` -------------------------------- ### Use destroy() Method to Cleanup Infinite Scroll Instance Source: https://context7.com/metafizzy/infinite-scroll/llms.txt The destroy() method removes the Infinite Scroll instance, cleaning up event listeners, restoring hidden elements, and removing internal registry entries. It's useful for disabling infinite scrolling or reinitializing with new options. ```javascript let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post', history: 'replace', button: '.load-next-button', hideNav: '.pagination' }); function disableInfiniteScroll() { infScroll.destroy(); } function reinitialize() { if (infScroll) infScroll.destroy(); infScroll = new InfiniteScroll('.container', { path: '/new-path/{{#}}', append: '.post' }); } ``` -------------------------------- ### Handle JSON Responses with Infinite Scroll Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Configure Infinite Scroll to process loaded content as JSON data instead of HTML documents. This is useful for APIs that return structured data. The `load` event provides access to the parsed JSON object, allowing you to manually render the content. A 204 No Content response can signal the end of the pages. ```javascript // Load JSON data let infScroll = new InfiniteScroll('.container', { path: '/api/posts?page={{#}}', responseBody: 'json', append: false // Don't auto-append, handle manually }); infScroll.on('load', function(data, path, response) { // data is parsed JSON object data.posts.forEach(post => { let article = document.createElement('article'); article.className = 'post'; article.innerHTML = `

${post.title}

${post.excerpt}

`; document.querySelector('.container').appendChild(article); }); }); // Return 204 status to signal last page // Server response: // HTTP/1.1 204 No Content ``` -------------------------------- ### Select Content to Append Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Defines which elements from the loaded pages should be appended to the main container. This is specified using a CSS selector. If `append` is set to `false`, the library will only trigger events without modifying the DOM, allowing for custom data handling. ```javascript let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post' }); ``` ```javascript let infScroll = new InfiniteScroll('.gallery', { path: '/photos/page/{{#}}', append: '.photo, .video' }); ``` ```javascript let infScroll = new InfiniteScroll('.container', { path: '/api/data/{{#}}', responseBody: 'json', append: false }); infScroll.on('load', function(body, path, response) { // Manually handle loaded data console.log('JSON data:', body); // Custom rendering logic here }); ``` -------------------------------- ### Masonry Grid Item HTML Structure Source: https://github.com/metafizzy/infinite-scroll/blob/master/sandbox/unsplash-masonry.html Defines the HTML structure for a single grid item, containing an image and a caption with a link to the photographer's Unsplash profile. This structure is intended to be dynamically populated with data from the Unsplash API. ```html
Photo by {{user.name}}

{{user.name}}

``` -------------------------------- ### Configure checkLastPage Option for Infinite Scroll Source: https://context7.com/metafizzy/infinite-scroll/llms.txt The checkLastPage option automatically detects the final page by checking for the presence of a specified selector. It can be set to true for default path selector detection, a custom selector string, or false to disable automatic detection. The 'last' event is emitted when the last page is reached. ```javascript let infScroll = new InfiniteScroll('.container', { path: '.pagination__next', append: '.post', checkLastPage: true }); let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post', checkLastPage: '.pagination__next' }); let infScroll = new InfiniteScroll('.container', { path: function() { if (this.pageIndex >= 50) return false; return `/api/page/${this.pageIndex + 1}`; }, append: '.post', checkLastPage: false }); infScroll.on('last', function(body, path) { console.log('Reached last page'); document.querySelector('.end-message').style.display = 'block'; }); ``` -------------------------------- ### Manage Browser History with Infinite Scroll Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Configure Infinite Scroll to update the browser's URL and history as users scroll. Options include replacing the current URL, creating new history entries for back button support, or disabling history management entirely. It also shows how to hook into history changes for analytics or UI updates. ```javascript let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post', history: 'replace', historyTitle: true // Update document.title from loaded pages }); let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post', history: 'push', historyTitle: true }); let infScroll = new InfiniteScroll('.container', { path: '/blog/page/{{#}}', append: '.post', history: false }); infScroll.on('history', function(title, path) { // URL has changed console.log('Current page:', path); // Update analytics, breadcrumbs, etc. }); ``` -------------------------------- ### CSS for Scrollable Container Source: https://github.com/metafizzy/infinite-scroll/blob/master/sandbox/container-scroll.html This CSS defines a scrollable container with a fixed width and height, enabling vertical scrolling while hiding horizontal overflow. It's commonly used to create specific areas for content loading. ```css .sidebar { width: 300px; height: 400px; overflow-y: scroll; overflow-x: hidden; border: 1px solid #CCC; } .post { margin-top: 0; font-size: 12px; } ``` -------------------------------- ### Scroll Within Element Using Infinite Scroll Source: https://context7.com/metafizzy/infinite-scroll/llms.txt Enable infinite scrolling within a specific container element, rather than the entire window. This is useful for components like modals or sidebars. You can either use the container itself as the scrollable element or specify a selector for a different scrollable child. ```javascript // Scroll within specific element let infScroll = new InfiniteScroll('.scrollable-container', { path: '/blog/page/{{#}}', append: '.post', elementScroll: true, // Use the container element itself scrollThreshold: 300 }); // Or specify different scroll element let infScroll = new InfiniteScroll('.content-container', { path: '/blog/page/{{#}}', append: '.post', elementScroll: '.scrollable-wrapper', // Selector for scroll element scrollThreshold: 300 }); ``` ```html
...
``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.