How to set scrollTop position for a new page

I have a page that always has the same menu on the left side of the page. Clicking on the href opens a new page, but it scrolls back to the top of the page. I want the scrollTop position of the new page to be what it was on the previous page.

$('a').click(function(e){
  var scroll = $(window).scrollTop();
  event.preventDefault();
  var targetLink = $(this).attr('href'); 
  window.open(targetLink, '_self','top=scroll', 'top=500'); // top position dosent work for me, top position=scroll
});

      

How can I archive this?

+3


source to share


2 answers


Basically you cannot set the scroll position if you open a new page in the same window. If you open a new page in a new window, you can set the scroll position as shown below:

var win = window.open(targetLink, '_blank',''); 
setTimeout(function(){win.scrollTo(0,scroll);},1000);

      

If you open the page in the same window then below is the workaround:



var win = window.open(targetLink+"?scroll="+scroll, '_self',''); 

      

Here we have added the scroll value at the end of the link as a request parameter, I hope you know about the request parameter. Then on the second page, we have to put below code to make it scrollable.

var href = window.location.href;
var scrollPos = href.substring(href.indexOf("scroll")+7);
window.scrollTo(0,parseInt(scrollPos));

      

+2


source


The redirect url must include a querystring parameter which gives the top position that the new page should load

var targetLink = $(this).attr('href') + '&top=' + scroll;

      



Then on the next page to load, use JS / jquery to set the top position for that value if found in the request.

+3


source







All Articles