1

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 .

2 Answers2

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>
paradigm111
  • 388
  • 1
  • 2
  • 10
  • I need to use this in a tag onclick, and then page raloading with get parameters in url, after reloading page is not keeping scroll position. I think that I need to keep scroll_position = window.scrollY; in cookie or in session, can You help me doing that way? – David Tumanyan Jan 26 '22 at 09:42
1
<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>