Home / Snippets / Use Alpine JS Intersect Plugin Instead of Defining Intersection Observable
Use Alpine JS Intersect Plugin Instead of Defining Intersection Observable cover

Use Alpine JS Intersect Plugin Instead of Defining Intersection Observable

1.8K

3 years ago

0 comments

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
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this