Skip to content Skip to sidebar Skip to footer

Maintain Scroll Position In Javascript Window.open()

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:

Solution 1:

<a href="#" onclick="window.open('myPage.aspx');return false;">OpenNewWindow</a>
  • javascript: is not required in event attributes.
  • You were not returning false from the event handler, so the link was being following, it was equivilent to <a href="#">Scroll to top</a>.

Solution 2:

<a href="javascript:void()" onclick="window.open('myPage.aspx');">OpenNewWindow</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.

Solution 3:

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.

Solution 4:

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;">OpenNewWindow</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.

Post a Comment for "Maintain Scroll Position In Javascript Window.open()"