skip to Main Content

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


  1. Chosen as BEST ANSWER

    Thank you, here's how I managed to solve it

    <body x-data="{ isShowing: false }" 
    @scroll.window = "isShowing = (window.pageYOffset > 150) ? true : false">
    
        <div id="back_To_Top" x-show="isShowing" 
            
            <p class="is-size-7">Back to top</p>
    
        </div>
    
    </body>
    

  2. 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

    <body x-data="{show_backToTop: false}"
          @scroll.window="show_backToTop = window.pageYOffset > 30"
    >
       <!-- simple style for the sticky button --> 
       <style> 
           .scrollTop{
               position: fixed;
               top: 0;
               overflow: hidden;
               z-index: 10;
           }
       </style>
    
        <div :class="show_backToTop ? 'block' : 'is-hidden'">
    
            <div id="back_To_Top"
                 x-ref="backTotop"
                 @click="window.scrollTo({top: 0, behavior: 'smooth'})"
                 class="scrollTop"
            >
    
            <p>Back to top</p>
            </div>
    
        </div>
    
        <table style="width:100%">   <!-- this is only to fill out the page for testing -->
    
            <template x-for="i in 100">
    
                <tr>
                    <td x-text="i"></td>
                    <td>aaa</td>
                    <td>bbb</td>
                    <td>ccc</td>
                    <td>ddd</td>
                </tr>
    
            </template>
    
        </table>
    
    </body>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search