Search code examples
jquerycssjquery-animatescrolltop

Animate scrollTop but I can't use $('html,body').animate({scrollTop: 0}, 'slow');


I am very new to jQuery so please don't mind me.

I have this style

html, body{
    height: 100%;
    overflow: auto;
}

And this script

$(document).ready(function() {
    $('#guide-wrap').scrollTop($('#main').position().top);
});

So when the window loads, it jumps to div with id main I want it to animate but since I have height: 100%; overflow: auto; I cannot use this script:

$('html,body').animate({scrollTop: 0}, 'slow');

Or maybe I don't know how to do it. I know it may look very obvious to you guys but I am very new and I've google a lot before decided to post here. Please anyone help me.


Solution

  • $('html, body').animate({scrollTop: 0}, 'slow'); is perfectly valid code for an animated scroll. However, it makes no sense to have an animation to scroll to the top of the page on a $(document).ready(), as a page will automatically be at the top by default.

    If you're looking for the scrolling to trigger on a hyperlink click, you need to remember to pass e.preventDefault() to the click event to prevent the default behaviour. If the link is pointing to the same page (such as with #), it will 'jump' to the top unless this behaviour is prevented.

    Here's a working example (scroll down to see the link):

    $(".scroll-top").on("click", function(e){
       e.preventDefault();
       $('html, body').animate({scrollTop: 0}, 'slow');
    });
    .tall {
      height: 200vh;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="tall">Top of the page</div>
    
    <a href=# class="scroll-top">Scroll Up</a>

    Hope this helps! :)