Maintain scroll position in JavaScript window (). Window ()

How to save the scroll position of the parent page when opening a new window using window.open ()? The parent page will return to the top of the page.

Here is my current code:

<a href="#" onclick="javascript: window.open('myPage.aspx');"> Open New Window </a> 
+4
source share
4 answers
 <a href="#" onclick="window.open('myPage.aspx');return false;">Open New Window</a> 
  • javascript: not required in event attributes.
  • You did not return false from the event handler, so the link went, it was equivalent to <a href="#">Scroll to top</a> .
+9
source
 <a href="javascript:void()" onclick="window.open('myPage.aspx');">Open New Window</a> 

Must do it. As others have noted, # tries to jump to a non-existent anchor, which will cause the browser to move up. You do not want to remove the href attribute because some browsers do not process <a> tags without href attributes as styling links, and you will need to define additional CSS rules to make the link look like other links to your site.

Also, why is there an href attribute, and then try to block the event, always returning false from your handler. In my opinion, this method is cleaner than the others offered here.

+1
source

I think the problem is that your link points to empty # ( href="#" ), which the browser interprets as "top of page".

Try removing the href attribute from the anchor tag. The onclick attribute should be sufficient for what you need.

0
source

It’s good to keep the page accessible for those who don’t have javascript, or disable it:

 <a href="myPage.aspx" target="_blank" onclick="window.open('myPage.aspx');return false;">Open New Window</a> 

Target = "_ blank" should open in a new window (or tab). If the client does not have JS, it will still open the page, just not in the window invoked by JS.

0
source

All Articles