'Save scroll position while doing php get request in same page

I have list of company workers. When I click to a worker, in corner of page showing workers image from mysql database. and mysql SELECT parameters I get from url:

Example:

<a href="<?php echo '?imgid=' . $imgID ?>">John SMITH</a>

How can I save my current scroll position when I'm clicking to .



Solution 1:[1]

You can do

var scroll_position = window.scrollY;

and to scroll there:

window.scrollTo(0, scroll_position);

You can test these out with this code in a new HTML file:

<div style="height: 400px;"></div>
<input type="button" value="Submit" id="submit" />
<div style="height: 2000px;"></div>
<script>
document.querySelector("#submit").onclick = function () {
    var scroll_position = window.scrollY;
    alert(scroll_position);
    window.scrollTo(0, 100);
}
</script>

Solution 2:[2]

<body onload="restoreScrollPos()">  

  <a onclick="setScroll()" href="<?php echo '?imgid=' . $imgID ?>">John SMITH</a> 

</body>

<script> 
function setScroll() {
    let scroll = window.scrollY;
    let scrollString = scroll.toString();
    localStorage.setItem("scrollPosition", scrollString);
}


function restoreScrollPos() {
    let posYString = localStorage.getItem("scrollPosition");
    let posY = parseInt(posYString);
    window.scroll(0, posY);
    return true;
}
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 David Tumanyan