Somepub
Somepub

Reputation: 435

How to I set scrollTop position for new page

I have a page that always has the same menu on the left side of the page. When clicking on a href, the new page opens, but it scrolls back to the top of the page. I want the scrollTop position of the new page to be what it was in 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 that?

Upvotes: 3

Views: 1631

Answers (2)

Nishesh Pratap Singh
Nishesh Pratap Singh

Reputation: 2181

Basically you can't set scroll position if you are opening new page in the same window. If you open new page in new window then you can set scroll position as shown below :

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

In case you are opening the page in same window, then below is the workaround for that :

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

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

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

Upvotes: 1

Yaakov Ellis
Yaakov Ellis

Reputation: 41490

You should include a querystring parameter in your redirect url that gives the top position that the new page should load

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

Then on the next page that loads, use JS/jquery to set the top position to that value if it is detected in the querystring.

Upvotes: 2

Related Questions