Interactivity with Alpine.js
How TailTemplates HTML templates use Alpine.js for sliders, popups, dropdowns and the sticky navbar.
A few parts of our HTML templates need JavaScript for interactivity, such as carousels, popups, dropdowns and the mobile menu. Tailwind CSS pairs nicely with Alpine.js, so that's what we use.
Adding Alpine.js
Alpine.js is already included in the templates that need it. If you copy a section into another project, add the Alpine.js script inside the head tag:
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
You can also download the file and host it yourself.
Sticky navbar
The templates' header is positioned absolute by default. To make it stick to the top of the page once the visitor scrolls, track the scroll position on the body tag:
<body
x-data="{ scrolledFromTop: false }"
x-init="scrolledFromTop = window.pageYOffset >= 50"
@scroll.window="scrolledFromTop = window.pageYOffset >= 50"
>
...
</body>
Then remove the absolute class from the header tag and switch its classes based on that value:
<header
:class="scrolledFromTop
? 'fixed z-50 bg-white/80 shadow-sm backdrop-blur-sm'
: 'absolute'"
>
...
</header>
Note: Alpine.js variable names are case-sensitive, so scrolledFromTop must be spelled the same way in both places. You can change the background color or any other classes to match your design.