0
votes

I've got JQuery running and I'd like to use a scrollTop animation to move the window back near the top (about 240px, though somewhat variable) as the callback of an AJAX call that will replace a large chunk of HTML content on the page.

I'm using:

$("html, body").animate({ scrollTop: someNumericalVariable });

The problem I run into is that, when this code runs with no delay or timeout, the window will do a very small scrolling animation to a location that is nowhere near desired. When I add a some arbitrary delay (at least 1 to a few seconds), the window may or may not end up in the desired location, but the animation is hardly an animation (it acts more like 2 separate scrollTop calls - it will quickly jump upward, wait a second, then jump upward again to the correct spot).

When I run the code separately (not as the callback in the middle of a bunch of HTML rendering), the animation seems to work properly.

Any ideas? Thanks in advance.

1
Why are you trying to do a scroll during page rendering? Why not wait until page is fully loaded before doing something like this? - Sparky
@Sparky672 it's so the page is at the top ready for when the content from the AJAX call is rendered - rickyduck
Is there a way to detect when dynamically added HTML has rendered? - dchang

1 Answers

0
votes

What you'll want to do is animate the scrollTop() position after the ajax call has completed and you've processed the data. For example:

$.ajax({
  url: "data.html",
  success: function(html) {
    $('#content').append(html); // process data first

    var someNumericalVariable = randomCalculation(); // do whatever calculation you need to do to figure out scrolltop
    $("html, body").animate({ scrollTop: someNumericalVariable }); // animate scrolltop
  }
});

If something isn't working right for you, post some code or make a jsFiddle and we'll have a look to find out what's going on.