3

I am having an issue trying to scroll the browser window immediately following jQuery load. The content loads fine, and the function called once load is complete is being called. However, I can only get the page to actually scroll if I set a timeout for 300ms as such:

frame.html("#box").load("loadedfile.php", function(){
   setTimeout(function() {
       $('html,body').animate({
          scrollTop: $("#framed").offset().top
          }, 750);
       },300);
    });

It appears that the load complete function is executing after the content has been loaded, but before the browser is able to scroll (as the page that hosts the script is not initially long enough to have scrollbars activated).

My workaround feels sloppy and probably is. Is there a better way to be handling this? The timeout does not seem like a reliable way to handle this.

I have tried window.scrollTo as well as the jQuery scrollTo plugin in additional to .animate

Owen McAlack
  • 399
  • 10
  • 28
  • 1
    Out of interest, have you tried setting the timeout to 0? Because JS is single-threaded, sometimes dropping out of execution to allow the UI to update is necessary (in which case using a timeout is just fine). – Vala Aug 24 '12 at 10:09
  • This actually worked for me today. Yesterday, I kept lowering the timeout, and it did not work when set to 100ms. Today it is now working with both 0 and 100. – Owen McAlack Aug 24 '12 at 18:27
  • ... I did just reboot, could the browser have lagged updating the UI? If so, that would be of concern for users with slow systems. – Owen McAlack Aug 24 '12 at 18:33
  • 1
    I think simply returning from the function you're in is enough to allow for the UI to refresh if it wants to - a delay of 0 doesn't mean it'll be executed instantly, only that it'll be executed "as soon as possible", which may well be after other things complete. It generally wouldn't hurt to let there be a small delay for other things to have a shot as well though, but I generally keep that down to 25-50. – Vala Aug 24 '12 at 20:15

2 Answers2

2

You can use ajax call to laod an external page and on success of that you can all the scroll animation.

$.ajax({
        url: 'loadedfile.php',
        dataType: "html",                 // <-- set dataType to "html"
        success: function(response) {
            $("#box").html(response).fadeIn(1000); // <-- added fadeIn()
        $('html,body').animate({
            scrollTop: $("#framed").offset().top
          }, 750);
        }
    })

Hope it does work for you. If not please do provide the link to view your problem practically, so that it can be sorted out.

1

This code is working for me

lastElementTop = $('#id').position().top;
scrollAmount = lastElementTop  +- something;
$('html,body').animate({scrollTop: scrollAmount},1000);
Abhishek Goel
  • 18,785
  • 11
  • 87
  • 65