By default, you can define an Intersection Observer which is a bit a challenge for beginners but instead, you can make use of the Alpine Js Intersect plugin.
Example: Infinite Pagination
If you have read the tutorial for How to Implement Laravel Livewire Infinite Pagination then you might come across the code to load more data when the user scrolls at the end of the page.
@if($hasMorePages) <div x-data="{ init () { let observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { @this.call('loadPosts') } }) }, { root: null }); observer.observe(this.$el); } }" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8 mt-4" > @foreach(range(1, 4) as $x) @include('partials.skeleton') @endforeach </div> @endif
So the code above will get initialized when the page is at the bottom of the page and when the user view the partials skeleton, then more post will be loaded.
Using Alpine JS Intersect Plugin
Now when you use Alpine JS intersect Plugin, you can simplify the whole thing with the code below.
@if($hasMoreData) <div x-data x-intersect="@this.call('loadMoreData')" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-x-4" > @foreach(range(1, 4) as $x) @include('partials.skeleton') @endforeach </div> @endif
So instead of observing the element manually, you can just specify "x-intersect" and call the method when the user scrolled to the bottom of the page.
Related Snippet
Leave a reply