Strattic Developers by Elementor

Front-End Only Load More Example

While Strattic offers pagination for blogs and other post types out of the box, that may not be your style.

There are times when you may want a quick way to test or implement a “Load More” button instead of asking your users to click through paginated pages. If our awesome Load More Example article doesn’t suit your needs, try the below implementation.

Example original JS code (that is, code that will not work out of the box on Strattic, please adjust as you need):

window.onload=function() {

	/**
	 * The level of pagination.
	 */
	let pagination = 2;

	/**
	 * Handle click events.
	 */
	window.addEventListener(
		'click',
		function( e ) {

            // Whatever the ID of your load more button is.
			if ( 'strattic-more-button' !== e.target.id || false === pagination ) {
				return;
			}

			// Run an AJAX request for the next page.
			let request          = new XMLHttpRequest();
			request.responseType = 'document';
			request.open(
				'GET',
				'/blog/page/' + pagination,
				true
			);
			request.onreadystatechange = function() {

				if ( request.readyState == 4 && request.status == 200 ) {
					// Pull the required content from the AJAX string.
					let ajax_content = request.responseXML.querySelector( '#strattic-more-content' );

					// Add the required content to the current page.
					let page_content       = document.getElementById( 'strattic-more-content' );
					page_content.innerHTML = page_content.innerHTML + ajax_content.innerHTML;

					pagination++;
				} else if ( request.status == 404 ) {
					pagination = false;
				}

			}
			request.send();
		}
	);
}

Note: this code will throw an error in the browsers console (but not on your site) once it runs out of pagination items. That is, if you try to click on the more button once there are no more items left, it will trigger a console error. You can handle that situation however you like, for example, adding a visual note to the user that “No more posts are available”.

Black Friday 20% Off
days
hr
min
sec