Philip Thomson
Philip Thomson

Reputation: 173

Prevent full page scrolling up on load()

I am using .load() to refresh the contents of a div every 5 seconds.

When the div updates, the whole page will scroll back up to the top. Is there any way to prevent this from happening?

<body>    
    <app-header condenses reveals effects="waterfall">
      <app-toolbar>
       <div main-title>Title</div>
       <a href="./login/logout.php" tabindex="-1"><paper-button class="custom white" raised>Log Out</paper-button></a>
      </app-toolbar>
    </app-header>

    <div id="loadcards"></div>
</body>
$("#loadcards").load("getGraph.php");

$(document).ready(function(){
  setInterval(function(){       
     $("#loadcards").load("getGraph.php");
  },5000);
});

Upvotes: 1

Views: 1543

Answers (1)

FvB
FvB

Reputation: 723

Your page scrolls back to the top when you reload because your browser very briefly does not have any content for your div. This causes the content of your page to become too small to require a scrollbar, but when the content is reapplied it might grow large enough to require a scrollbar yet again.

Option 1

You could set the Y offset to the top of your page everytime before the reload is called, then scroll back to that offset whenever the page finishes reloading (or at least as far down as possible if the page is smaller than before).

You can obtain the current offset from the top of the window with the following code:

var offsetY = $(window).scrollTop();

If you want to scroll back to where you were before, you can do so by calling the following:

$('html, body').animate({
    scrollTop: $(this).offset().top
}, 300);

This will gradually scroll, but you can set 300 to 0 if you want it to scroll instantly.

Depending on the efficiency with which your page loads, you'll probably still see a jump in the page contents.

Option 2

You can alternatively put your entire DIV inside a container with a fixed height, and reload the contents inside. You should set at least a min-height on the container div.

<div style="min-height: SOME_VALUE">
    <div id="loadcards"></div>
</div>

Set SOME_VALUE to whatever comes closest to your actual page size. This should prevent the page jump as well, but will cause your page to have a minimal height even when the actual contents are smaller.

Option 3

The most advanced solution would be to use a container DIV and set the height to whatever the LoadPage height is just before you reload. This way it will only reset AFTER you reload your page.

<div id="cardscontainer" style="min-height: SOME_VALUE">
    <div id="loadcards"></div>
</div>

With the following changes to your JS:

setInterval(function(){
    $("#loadcards").load("getGraph.php");
    $('#cardscontainer').height($('#loadcards').height());
},5000);

EDIT: I swapped the 2 functions inside the SetInterval callback function because it would result in weird behaviour if the LoadCards DIV would be smaller than before.

Upvotes: 1

Related Questions