javascript – Return to the same point on the page that I left when I hit "back"

Question:

How can I get back to where I am when I hit a link on a page on the same website and then hit back?

Practical case:

In www.micasa.es I have a list of properties with thousands of results in a search and if I enter one of the advertised flats, then how can I return to the same point in the list from which I left?

Currently in the micasa.es portal we have a continuous list that is reloaded as we scroll and how we have that problem (How to return to the same point in the list when we see an ad and then want to return) what we are doing in opening the file of the property that we want to see in a new window, but that is not a good system, it fills the user's browser screen with tabs and when he wants to return to where he was, there is no back button and he does not know which of the tabs he has open is the results.

It is a bit confusing to explain it in writing, but I think I have explained myself more or less.

If you can help us, I would appreciate it.

All the best

Answer:

In www.micasa.es I have a list of properties with thousands of results in a search and if I enter one of the advertised flats, then how can I return to the same point in the list from which I left?

You need to save the coordinates before leaving the page. You can save the coordinates in a cookie or in sessionStorage to be more practical.

For example:

function saveCoords (e) {
  sessionStorage.setItem("coords", JSON.stringify({
    y: window.scrollY,
    x: window.scrollX
  }));
}

function posicionate () {
  var coords = JSON.parse(sessionStorage.getItem("coords"));
  if (coords) {
    window.scrollTo(coords.x, coords.y);
  }
}

The posicionate method must be executed when the body is loaded ( <body onload="posicionate()> ) and the saveCoords function must be executed when the link is clicked. Internally, the coordinates of the scrollbar will be saved in a serialized object to be saved in the sessionStorage and, when loading the body, these coordinates will be obtained to move to where the user has stayed.

Scroll to Top