tags:

views:

1275

answers:

5

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>
+2  A: 
<a href="#" onclick="window.open('myPage.aspx');return false;">Open New Window</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>.
Grant Wagner
A: 

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.

matt b
A: 
<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.

pkaeding
A: 

Thanks pkaeding..i was having the same problem..and its solved now.. :)

A: 

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.

bucabay