Scroll down the page when restarting with JS

4

I was hoping that when the page was loaded, it would automatically go to the end of it. I do not want to use jquery because the project is relatively simple. It is not necessary. I used the following code:

<body onload="toBottom();">

</body>
function toBottom(){
  var elem = document.querySelector("body");
  elem.scrollTop = elem.scrollHeight;
}

It works when loading page, okay! Only when I give refresh not. Only if I close the page, and sign in again. How do I resolve this?

    
asked by anonymous 02.12.2016 / 18:47

2 answers

3

Try to use onload within your javascript :

window.onload = toBottom;

function toBottom() {
  setTimeout(function() {
    window.scrollTo(0,document.body.scrollHeight);
  }, 0);
}
    
02.12.2016 / 19:02
4

This way I tested here giving F5 and reload the page and it works perfectly.

I edited with the function create br to stay with 30 thousand brs on the page kk

window.onload = function() {
  criaBr();

  toBottom();
};

function criaBr(){
  var body = document.querySelector("body");
  var br = "<br/>";
  for(var i = 0; i < 10; i++){
      br += br;
  }
  
  body.innerHTML += (br + "<button onclick='refresh()'> Refresh </button>");
}

function refresh(){
	location.reload();
}

function toBottom(){
  var elem = document.querySelector("body");
  elem.scrollTop = elem.scrollHeight;
}
<body>
b


</body>
    
02.12.2016 / 19:14