I’ve been practising with Alpine.JS and attempted to create a back to top button. I’ve got stuck as the button does not hide at all, I’m trying to get Alpine to recognise when the user scrolls down to a certain height, then show the button.
"is-hidden" is a bulma css property
Here is the code:
<body x-data="{show_backToTop: true}"
@scroll.window="show_backToTop = (window.pageYOffset > 200) ? false : true">
<!-- back to top scroll button -->
<div class="show_backToTop ? 'block' : 'is-hidden' ">
<div id="back_To_Top"
x-ref="backTotop"
x-data @click="window.scrollTo({top: 0, behavior: 'smooth'})" // ignore this, this is the script to return to the top of page
class="scrollTop">
<p>Back to top</p>
</div>
</div>
</body>
2
Answers
Thank you, here's how I managed to solve it
One problem is in the class of the button: to make it dynamic you have to precede it with a colon – more info here
Another problem is in the logic: the show_backToTop flag should be initialized to false and set to true if the page is scrolled down
Here a working example – I have reduced the offset scroll to 30