Onelio
Onelio

Reputation: 323

Loading a page with xhttp

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

Upvotes: 0

Views: 396

Answers (2)

Onelio
Onelio

Reputation: 323

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

e.preventDefault();
return false;

Upvotes: 0

Türerkan İnce
Türerkan İnce

Reputation: 44

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();
}

Upvotes: 0

Related Questions