How to Create a Scroll to Top Button in Hyvä Using Alpine.js and Tailwind CSS

Create a Scroll to Top Button in Hyvä

In this guide, we’ll show you how to create a scroll to top button in the Hyvä theme using Alpine.js and Tailwind CSS. This scroll to top button will enhance your Hyvä-themed Magento store’s user experience, allowing visitors to easily navigate back to the top of the page with a smooth, lightweight solution. Utilizing Alpine.js for the functionality and Tailwind CSS for styling, this integration ensures performance and simplicity in the Hyvä environment.

In your PHTML file (e.g., backtotop.phtml), insert the following code:

<div id="backtoTop" class="bg-gray-300 text-center float-right cursor-pointer p-2 fixed right-5 bottom-5">
  <?= $escaper->escapeHtml(__('Back to top')) ?>
</div>

<script>
{
    const back2Top = document.querySelector('#backtoTop');
    back2Top.addEventListener('click', (e) => {
        e.preventDefault();
        window.scroll({ top:0, left:0, behavior: 'smooth'});
    });
}
</script>

Hyvä Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *