0

I am implementing a web page with dynamic content. In particular, I have a "div" which I update its content in the following way:

This is the "div":

<div id="informationONDevices"></div>

I proceed to delete its content:

document.getElementById("informationONDevices").innerHTML = "";

Finally, I insert "divs" inside the original "div" (the code that follows is inside a loop):

var element  = document.createElement("div");

element.innerHTML = "<h3>Dades de la sonda amb ID: " + this.responseXML.getElementsByTagName('addONDevices')[count1].childNodes[0].nodeValue + " i Alias: " + this.responseXML.getElementsByTagName('aliasONDevices')[count1].childNodes[0].nodeValue + "</h3>" + "<br><br>"
+ "<span class='title'>Actual</span><br>";

document.getElementById("informationONDevices").appendChild(element);

The problem is that every time I update the content of the "div" the page does autoscroll and does not stay where it was. Any solution? I've been looking for and trying a lot of things and none has helped me.

Thank you very much!

Kane12
  • 3
  • 3
  • What's the event that triggers `document.getElementById("informationONDevices").innerHTML = "";`? – Christian Vincenzo Traina Jun 09 '18 at 09:42
  • try using overflow:hidden; in css or your body or element to which you are appending – MJN Jun 09 '18 at 09:43
  • @CristianTraìna The event that triggers that is the response to a `XMLHttpRequest()` object. Therefore, what I do is make a request to a server and when I have a response I update the page. – Kane12 Jun 09 '18 at 09:49
  • Possible duplicate of [Prevent automatic browser scroll on refresh](https://stackoverflow.com/questions/7035331/prevent-automatic-browser-scroll-on-refresh) – Samuel Hulla Jun 09 '18 at 09:55
  • @Manjunath That's not working for me... – Kane12 Jun 09 '18 at 10:03
  • @Rawrplus But these post is for browser's refresh. Isn't my case. My problem is that, during a few microseconds, the div container is empty and it seems that because of this the webpage scrolls automatically. Any ideas? – Kane12 Jun 09 '18 at 11:13

1 Answers1

0

After spending hours searching for information, I decided to try things out. Here is the solution:

var oldPositionSB = window.pageYOffset;

document.getElementById("informationONDevices").innerHTML = "";

…

document.getElementById("informationONDevices").appendChild(element);

window.scrollTo(0, window.pageYOffset + (oldPositionSB - window.pageYOffset));
Kane12
  • 3
  • 3