Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retain scrollbar position even after reloading using javascript

I have requirement where if I click on a checkbox the value gets submitted and hence the page gets reloaded. Now, to click another checkbox, i need to scroll down again which is not a better idea. So, now I want to retain my scrollbar position even after page gets reloaded. Is there any method in javascript to do that? I have tried the below code, but there was no luck.

<input type="checkbox" onclick="myFunction()"/> One <br/>

function myFunction() {
         document.body.scrollTop = 500px;
        }

I also browsed many websites but nothing worked for me. Please help me with this issue.

Thanks.

like image 759
Shruthi Sathyanarayana Avatar asked Dec 14 '15 07:12

Shruthi Sathyanarayana


People also ask

How do you keep the scroll position?

Preserve scroll position allows you to maintain the same scroll location when you transition between two screens. This applies to scroll depth in a vertical scroll, as well as the user's location inside a horizontal scrolling element. Figma automatically preserves your scroll position for Smart Animate.

How can I retain the scroll position of a scrollable area when pressing back button?

store the position in cookies and after that use the cookie to scroll the page to exact position .

How do you maintain the scroll position react?

By default you can set the value of scrollPosition is 0 . Here I have used the sessionStorage to maintain the scroll position for demo purpose. You can also use the context API or redux store to manage it.

What does scrollTop return?

The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0. When used to return the position: This method returns the vertical position of the scrollbar for the FIRST matched element.


1 Answers

You can use session storage to store the position then get back to the position when the page is reloaded, like this:

$(window).scroll(function() {
  sessionStorage.scrollTop = $(this).scrollTop();
});

$(document).ready(function() {
  if (sessionStorage.scrollTop != "undefined") {
    $(window).scrollTop(sessionStorage.scrollTop);
  }
});

Here is the JSFiddle demo

like image 77
Ahs N Avatar answered Oct 22 '22 02:10

Ahs N