Tech

Alpine.js: Using x-intersect to Animate an Element When it Enters the Viewport

Photo of Zac VineyardZac Vineyard
January 1st, 2025

The key to getting x-interset to work, is that it has to be used within an Alpine object. The easiest way to do this is to add x-data to any parent element in the DOM.

Be sure you have Alpine.js installed and the Alpine Intersect plugin. To test this on a site, you can rely on CDN resources. Be sure to include the plugin before the core Alpine library.

<script defer src="https://cdn.jsdelivr.net/npm/@alpinejs/intersect@3.x.x/dist/cdn.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>

To have an object fade-in with an upward motion, all I do is use x-intersect to add a class to the element:

<div x-data>
  <div x-intersect="$el.classList.add('fadeInUp')">
	Some content here.
  </div>
</div>

Then I create an animation in CSS:

.fadeInUp {
    animation: fadeInUp 1s forwards;
    animation-delay: 0s;
}
@keyframes fadeInUp{
    0%{
        opacity:0;
        transform:translateY(20%)
    }
    to{
        opacity:1;
        transform:translateY(0)
    }
}

Copyright © Zachary Vineyard