13

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 the content:

$(document).ready(function () {
    var my_layout = $('#container').layout();
    $("a.item_link").click(function () {
        $("#loader").fadeIn();

        feed_url = $(this).attr("href");
        $.ajax({
            type: "POST",
            data: "URL=" + feed_url,
            url: "view.php",
            success: function (msg) {
                $("#view-area").html(msg);

                $("#loader").fadeOut();
            }
        });
        return false;
    });
});

So after the 'view-area' has loaded its content can I make the page auto scroll to the top?

CAbbott
  • 8,078
  • 4
  • 31
  • 38
Aaron Fisher
  • 645
  • 3
  • 8
  • 23

4 Answers4

29

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);
        }
Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
  • Thanks, this has worked perfectly! I just put the code in between $("#view-area").html(msg); and $("#loader").fadeOut(); and it worked! Thanks. – Aaron Fisher Mar 19 '12 at 20:53
  • Why it's not working on other selector? Like $('.section').animate({ scrollTop: 0 }, 0); But html, body selector working. – Jilani A May 19 '21 at 07:08
3

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

Icarus
  • 63,293
  • 14
  • 100
  • 115
1

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

PaulKoeck
  • 134
  • 3
0

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
);
Hannes Schneidermayer
  • 4,729
  • 2
  • 28
  • 32