Code for "Jump to top" button

Hey There,

Does anyone have a js code for a "jump to top" button for every knack page?

Tks!

Hi 371928693712, if you could help me with something else. The button is not working with search views that do not present automatically the results nor with modal pages. Is there a way to solve this issue? Tks!

It worked for the scroll down then when returning to top the button is still displayed. I would like to hide everytime the user was less then 50px from top.

Something like this:

$(window).scroll(function() {
if ($(this).scrollTop() >= 50) { // If page is scrolled more than 50px
$('#return-to-top').fadeIn(400); // Fade in the arrow
} else {
$('#return-to-top').fadeOut(400); // Else fade out the arrow
}
});

Try this (you can change the threshold to a number that works for you):

Knack.fn = Knack.fn || {}; 
Knack.fn.jumpToTop = function(){
    if (Knack.$(document).height() > Knack.$(window).height()) { //check if window has a scroll bar
        document.onscroll = function(){
            const scrollThreshold = 50; //change this to determine how far a user must scroll before seeing the button
            let hasScrolled = document.documentElement.scrollTop > scrollThreshold ? true : false;
            if (hasScrolled){
                Knack.$('#jumpToTopBtn').remove();
                Knack.$('.kn-view:last-child').after('<button class="kn-button" id="jumpToTopBtn">Jump to top</button>');
                
                Knack.$('#jumpToTopBtn').click(function(){
                    Knack.$(window).scrollTop(0); //scroll to top
                })
            }
        };
    }
}

//call on any scene render. Change this to view/scene renders if you want it on specific pages
$(document).on('knack-scene-render.any', function(event, scene) { 
    Knack.fn.jumpToTop(); //call the function to add jump to top button
});

Hi Kelson! It worked! Thank you!

I would like to add a function to only display the button when user scroll down at least 50px from top. How can I add that?

Thanks again!

Hi Guilherme, 

Here is the code to add a jump to top button for every knack page:

Knack.fn = Knack.fn || {}; 
Knack.fn.jumpToTop = function(){
    if (Knack.$(document).height() > Knack.$(window).height()) { //check if window has a scroll bar
        Knack.$('#jumpToTopBtn').remove();
        Knack.$('.kn-view:last-child').after('<button class="kn-button" id="jumpToTopBtn">Jump to top</button>');
        
        Knack.$('#jumpToTopBtn').click(function(){
            Knack.$(window).scrollTop(0); //scroll to top
        })
    }
}

//call on any scene render. Change this to view/scene renders if you want it on specific pages
$(document).on('knack-scene-render.any', function(event, scene) { 
    Knack.fn.jumpToTop(); //call the function to add jump to top button
});


Let me know if you need any additional help!

Best Regards, 
Kelson
kelson@ksensetech.com
http://www.ksensetech.com/knack/