Introduction
Here's how you can create a dead simple "back to top" button in your AlpineJs + Blade projects. It's a super useful component to have, and I've found myself building it a couple of times.
The Component
<div
x-data="{ show: false }"
x-on:scroll.window="show = window.pageYOffset >= 1000"
class="fixed bottom-8 right-8"
>
<button
x-show="show"
x-transition
x-on:click="window.scrollTo({top: 0, behavior: 'smooth'})"
class="shadow-lg bg-white p-2 rounded-full"
>
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
<path fill="currentColor" d="m11 7.825l-4.9 4.9q-.3.3-.7.288t-.7-.313q-.275-.3-.288-.7t.288-.7l6.6-6.6q.15-.15.325-.212T12 4.425q.2 0 .375.063t.325.212l6.6 6.6q.275.275.275.688t-.275.712q-.3.3-.713.3t-.712-.3L13 7.825V19q0 .425-.288.713T12 20q-.425 0-.713-.288T11 19V7.825Z"/>
</svg>
</button>
</div>
How The Code Works
First, we use the x-data
directive to initialise the AlpineJs component.
Next we'll usethe window.pageYOffset
attribute on the window object to check how far down the page we are. We only want to show the button when we're no longer at the top.
By using x-on:scroll
, and binding the listener to the window object by appending .window
to the listner, every time the user scrolls, this code will trigger. When the user scrolls past 1000px from the top of the page, show will be set to true.
Finally, we use the x-on:click
directive, along with the scrollTo
method on the window to scroll to the top, when a user clicks that button.
The Result
Here's how it looks. You might even be able to see it on the page right now.
Hope this helps! 🤙
No comments yet…