Reputation: 25270
How do I maintain the scroll position of the parent page when I open new window using window.open()? The parent page returns to the top of the page.
Here is my current code:
<a href="#" onclick="javascript: window.open('myPage.aspx');">
Open New Window
</a>
Upvotes: 5
Views: 6220
Reputation: 5295
It is good to keep the page accessible for those that don't have javascript, or have it disabled:
<a href="myPage.aspx" target="_blank" onclick="window.open('myPage.aspx');return false;">Open New Window</a>
The target="_blank" is to open in a new window (or tab). If the client does not have JS, then it will still open the page, just not in a JS invoked window.
Upvotes: 0
Reputation: 37643
<a href="javascript:void()" onclick="window.open('myPage.aspx');">Open New Window</a>
Ought to do it. As others have mentioned, the # is trying to go to a non-existent anchor, which will cause the browser to scroll to the top. You don't want to remove the href attribute, because some browsers don't treat <a>
tags without href attributes as links for styling purposes, and you would have to define additional CSS rules to ge thte link to look like other links on your site.
Also, why have an href attribute and then try to block the event by always returning false from your handler. In my opinion, this way is cleaner than the others proposed here.
Upvotes: 1
Reputation: 139931
I think the problem is that your link is pointing to an empty # (href="#"
), which the browser will interpret to mean "the top of the page".
Try removing the href attribute from your anchor tag. The onclick attribute should be enough for what you need.
Upvotes: 0
Reputation: 25931
<a href="#" onclick="window.open('myPage.aspx');return false;">Open New Window</a>
javascript:
is not required in event attributes.<a href="#">Scroll to top</a>
.Upvotes: 11