Home > Software engineering >  Posts Page in React js
Posts Page in React js

Time:11-13

I have posts page every post have id . how i can listen to scroll and save the current post_id that user can start where he left off ?

I wont to make thing like this : onUserSeePost : post postId to back_end

CodePudding user response:

Your question is not clear, Kindly add some code.

Add a scroll event listener. Store the scroll location in the localstorage, When the user returns to the page scroll him back to the location

//Event listener to store the scroll position
addEventListener("scroll", function (e) {
  // Get the new Value
  var newValue = e.target.scrollTop;
  //Subtract the two and conclude
  if (oldValue - newValue < 0) {
    console.log("down");
  } else if (oldValue - newValue > 0) {
    console.log("up");
  }
  // Update the old value
  oldValue = newValue;
});

//scroll him back
function scrollMe() {
  el.scrollTop = localStorage.getItem("myscroll");
}

CodePudding user response:

I don't know if I get the idea, for what you want to do, but if you want to be in the exact same position where the user left the scroll bar you could use the property of the window window.scrollY, you can see an example here, but I think you don't need a event handler, maybe you could use the localStorage API to do the trick, save that position then just check if there is some position saved in the localStorage and just do something like:

window.scrollY = 700 <= value in pixels, from where is going to be the scroll bar in the Y axis on the document.

  • Related