0

I have a little question that I want to ask.

First of all, I'm using JS for loading a page.

function ReLoad() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function () {
         if (xhttp.readyState == 4 && xhttp.status == 200) {
             document.getElementById("box").innerHTML = xhttp.responseText;
          }
       };
      xhttp.open("GET", "calc/index.html", true);
      xhttp.send();
 }

Now, My problem is while I'm inserting this index into the main page, because the page auto-scroll immediately to the start and I want to load the page without this annoying effect.

Please, Can someone help me? Thanks

Hamza Zafeer
  • 2,360
  • 13
  • 30
  • 42
Onelio
  • 313
  • 1
  • 4
  • 16
  • "the page auto-scroll immediately to the start" How are you triggering this XHR request? Is it by any chance with an ``? – Daniel Beck Mar 12 '16 at 14:24
  • OK. The reason I ask is that inserting new content to the DOM does not on its own cause the window to scroll to the top. `href="#"` is a common technique that *does* change the scroll position -- if you're not doing that, you must be doing something else not shown in your above code that changes the scroll position. You could paper over the problem by storing the current scroll position and setting it manually afterwards as suggested below, but that would be unnecessary extra work and wouldn't really fix the underlying issue. – Daniel Beck Mar 14 '16 at 18:16

2 Answers2

0

you can store the scroll position;

var currentPosition = window.pageYOffset || document.documentElement.scrollTop;

and reapply it:

window.scrollTo(0, currentPosition);

so your code would become:

function ReLoad() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function () {
     if (xhttp.readyState == 4 && xhttp.status == 200) {
         var currentPosition = window.pageYOffset || document.documentElement.scrollTop;
         document.getElementById("box").innerHTML = xhttp.responseText;
         window.scrollTo(0, currentPosition);
      }
   };
  xhttp.open("GET", "calc/index.html", true);
  xhttp.send();
}
0

I finally solved it adding this to the end of the code:

e.preventDefault();
return false;
Onelio
  • 313
  • 1
  • 4
  • 16