Scroll down when restarting with JS

Asked

Viewed 87 times

4

I was hoping that when the page was uploaded, it would automatically go to the end of the page. I don’t want to use jquery because the project is relatively simple. It’s 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 page loads, ok! Only when I give refresh no. Only if I close the page, and log in again. How to resolve this?

2 answers

4

This way I tested here giving F5 and Reload on the page and works perfectly.

I edited with the function creates br para n to stay with 30 thousand brs on 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>

  • In reality your solution only works because you are added items to HTML within the Javascript. If you leave the HTML fixed will not work.

  • 1

    It works yes, if look at the issues I had done otherwise, but not to get too big the code refatorei and I did so

3


Try to use the onload within your javascript:

window.onload = toBottom;

function toBottom() {
  setTimeout(function() {
    window.scrollTo(0,document.body.scrollHeight);
  }, 0);
}
  • Unfortunately the same result. Works, but not when refreshed.

  • @Ericki changed the function here, with the setTimeout works

  • Perfect! Thanks^^

Browser other questions tagged

You are not signed in. Login or sign up in order to post.