Scroll to top after Ajax content load

后端 未结 4 1310
执念已碎
执念已碎 2020-12-31 08:21

Is there anyway that I can make it so the page will automatically scroll to the top after the content has loaded (via Ajax)?

This is the code I have for displaying

相关标签:
4条回答
  • 2020-12-31 08:39

    Just use the scroll function

    scrollTo(0);
    

    If you want the jquery, then here is a good example with smoothing :)

    From the link:

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

    To put it in your code

    ...
            success: function (msg) {
                $("#view-area").html(msg);
                $("#loader").fadeOut();
                //Put code here like so
                $('html, body').animate({ scrollTop: 0 }, 0);
            }
    
    0 讨论(0)
  • 2020-12-31 08:46

    If you have no callback, try to bind an event listener:

    document.addEventListener(
        "load",
        function(event) {
            event.composedPath().forEach(function(dom) {
                if (dom.classList && dom.classList.value === "classOfLoadedContent") {
                    $(".div-to-be-scrolled").scrollTop($(".content").innerHeight());
                }
            });
        },
        true
    );
    
    0 讨论(0)
  • 2020-12-31 08:57

    You can do $(window).scrollTop(0);

    0 讨论(0)
  • 2020-12-31 08:58

    All ajax requests have a callback argument so use scrollTop(0). Check the jQuery documentation on how to use ajax callbacks.

    0 讨论(0)
提交回复
热议问题