Posts Learn Components Snippets Categories Tags Tools About
/

Use Alpine JS Intersect Plugin Instead of Defining Intersection Observable

Learn how to make use of alpine js intersect plugin instead of defining your own observable

Created on Jul 26, 2021

1804 views

Sometimes you might come across wanting to observe the user scroll behavior and perform some action when it hit some certain page height / reached an element that appears on the screen.

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

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)