An Alpine.js plugin to easily set CSS classes to an element when it enters the viewport.
Especially useful for animating elements when scrolling.
<!-- A little something like this.. -->
<div x-data x-intersect-class="is-visible"></div>
Click here to take a look at the examples (View Source)
You can use this plugin by either including it from a <script>
tag or installing it via NPM:
You can include the CDN build of this plugin as a <script>
tag, just make sure to include it BEFORE Alpine's core JS file.
<!-- This Plugin -->
<script defer src="https://unpkg.com/alpinejs-intersect-class@1.x.x/dist/cdn.min.js"></script>
<!-- Alpine Core -->
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
You can install Intersect from NPM for use inside your bundle like so:
npm install alpinejs-intersect-class
Then initialize it from your bundle:
import Alpine from 'alpinejs'
import intersectClass from 'alpinejs-intersect-class'
Alpine.plugin(intersectClass)
...
Use the x-intersect-class
Attribute to set the CSS class that should be added to the element once it comes to the browsers viewport.
<div x-data x-intersect-class="fade-in"></div>
Make sure that you have defined that class in your CSS files, like fade-in
in this example.
You can use the .once
modifier if you want to trigger the CSS class only on the first appearance of an element.
<div x-data x-intersect-class.once="fade-in"></div>
Control the threshold
property of the IntersectionObserver. This works the same way like it does with Alpines Intersect Plugin.
<div x-data x-intersect-class.threshold.75="fade-in"></div>
<div x-data="{ shown: false }" x-intersect="shown = true" :class="{ 'is-visible': shown }">
You definitely could. And if you are using the Intersect plugin already, then you probably should!
The point of the Intersect-Class plugin is to provide this functionality with as few attributes as possible so that frontend developers will actually use it.
Yes, you do. With x-data you define a Alpine.js Component.
Click here to read more about x-data in the Alpine.js documentation.
This is a known problem with JavaScript animations. It's because the JS takes a moment to initialize. The solution can be different depending on what kind of animation you want to run.
A good starting point could be the use of x-cloak. Initial use of the CSS class can also be helpful, like I did for the CSS animations demo.