Home > other >  Why is my scroll to top always animated? And how can I instantly travel to top?
Why is my scroll to top always animated? And how can I instantly travel to top?

Time:10-06

So I have this heavily animated website made and every time I apply "Back to top" code on my button, it always animates scrolling through the entire page until it reaches the top.

I want it to instantly take them to the top without any fancy scroll up effects which is what I am getting..

I have tried multiple scripts and they all get an animation for some reason (even if I search for script code that is supposedly not animated).

this is the current script I am using: (I have tried multiple but they all resulted in the same animated scroll up effect)

<!-- Back to top -->
    <script>
        var btn = $('#BackTop');
        $(window).scroll(function() {
            if ($(window).scrollTop() > 300) {
                btn.addClass('show');
            } else {
                btn.removeClass('show');
            }
        });

        btn.on('click', function(e) {
            // e.preventDefault();
            window.scrollTo({
                top: 0,
            })
        });
    </script>

These are the other scripts included in the page, could have any of these been effecting my scroll to top code perhaps?

<!-- Scripts -->
    <script type="text/javascript" src="./my-assets/js/jquery.js"></script>
    <script type="text/javascript" src="./my-assets/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="./assets/js/lib/gsap3/gsap.min.js"></script>
    <script type="text/javascript" src="./my-assets/js/scroll.js"></script>

    <!-- .cd-vertical-nav -->
    <script src="./my-assets/js/velocity.min.js"></script>
    <script src="./my-assets/js/velocity.ui.min.js"></script>
    <script src="./my-assets/js/main.js"></script>

    <!-- fade effect js -->
    <script src="./my-assets/js/aos/aos.js"></script>

Would appreciate any tips with what exactly am I doing wrong, because I really want it to be instant to top and not animated because the page I am working on is huge in a sense where I dont want the costumer to see the entire page scroll back up..

CodePudding user response:

It is just a matter of css properties on the document.

You can either specify the behaviour for the particular operation

window.scrollTo({ top:0, left:0, behavior: "instant"}); // using built in
$(window).scrollTo(0, {duration:0}); // using jquery

Other than that you could try changing the css properties of the document

html {
    scroll-behavior: auto;
}

CodePudding user response:

For that you don't even need JS. You can set empty or hidden div in top of you page and give it some id. And make your btn be a tag that links to it

<a href="#id">

Here is the example

Alternatives

If you want to use JS you can

document.getElementById("body").scrollIntoView()

Or JQuery

$(window).scrollTo(0, {duration:0})
  • Related