views:

61

answers:

4

How do I open a new window in javascript properly?

I've tried:

<a href='javascript:window.open("testing.html","mywindow","menubar=0,resizable=1,width=200,height=500,left=0,top=0");' >New Window</a>

This causes a new window to pop up but in Firefox it leaves the original page with a blank window saying "[object Window]". I've also had issues with IE as well.

How can I open a window that works in Firefox, IE, Safari and Chrome?

Bonus: If you can help in creating a link that is javascript degradable (I think that's the term).

+3  A: 

javascript: links are pretty old-school. Try it with an onclick attribute. And don't forget to return false in the onclick handler to prevent the main page from following the link too.

<a href="testing.html" onclick="window.open(this.href,'mywindow','menubar=0,resizable=1,width=200,height=500,left=0,top=0'); return false;">New Window</a>
Asaph
A: 

you could add void(0) to your javascript code which will prevent the browser from doing anything to the current window

<a href='javascript:window.open("testing.html","mywindow","menubar=0,resizable=1,width=200,height=500,left=0,top=0"); void(0)' >New Window</a>
Marek Karbarz
A: 
<a href='javascript:(function(){window.open("testing.html","mywindow","menubar=0,resizable=1,width=200,height=500,left=0,top=0")}();' >New Window</a>

Or make it a function:

<a href="file.html" class="popup">File</a>

<script>window.onload = function(){ 
document.getElementsByTagName('a').onclick = 
function(evt){ el = evt.target; if (el.className == 'popup'){
       window.open(el.href,"mywindow","menubar=0,resizable=1,width=200,height=500,left=0,top=0"); 
       return false; }; };</script>
CodeJoust
+2  A: 

By putting the script in the href property, the link will follow the string representation of the return value of the script.

The most backwards compatible way is to put the url and target in the link as regular attributes, and use the onclick event to open a window instead of following the link. By returning false from the event you prevent the link from being followed:

<a href="testing.html" target="_blank" onclick="window.open(this.href,this.target,'menubar=0,resizable=1,width=200,height=500,left=0,top=0');return false;">New Window</a>

If Javascript is disabled in the browser, it will follow the link instead and open it in a new window.

Use the target _blank to open a new window.

Guffa
thanks for the excellent explanation! Do you know if this works in IE6?
chris
@chris: It definitely works in IE6. I would expect it to work as far back as IE4 at least...
Guffa
@Guffa: great, thanks!
chris