Tuesday, May 15th, 2007

The One True Way to Open a Window in JavaScript

Category: JavaScript, Tip

<>p>Ryan Johnson shares his short tip on how to use JavaScript to open a window, letting users decide how they want to handle it, and supporting non-JavaScript clients:

  1. <a href="your_link" onclick="window.open(this.href,'window_name','options'); return false;"></a>

unobtrusively add on to an item:

javascript
< view plain text >
  1. $$('#mylink').each(function(link) {
  2.   link.onclick = function(){
  3.     window.open(this.href,'name','options');
  4.     return false;
  5.   };
  6. });

Most of us will see this as a no-brainer. I often wish that links that do rewriting would keep the link for copy and pastability.

Related Content:

22 Comments »

Comments feed TrackBack URI

Isn’t #mylink stands for an ID?… And of course with small landing pages and newsletters prototype is a no go but $$ is cute as always.

Comment by DeadCabbit — May 15, 2007

Dion, I love to see things like this pointed out! It’s far too often over looked. Taking it one step further (depending on the project) is to either give the link a class OR ID and/or traverse the DOM to drop in the onclick statement on page load.

Comment by Frederick Townes — May 15, 2007

Using proper event attachment and one “Event.stop” before return false may solve some strange behaviour in IE.

Comment by _Nec — May 15, 2007

I would love to see a mention in the post that the JavaScript code only works with the prototype framework and that it only adds an onclick event handler to the link with the id ‘mylink’ and not every link in the page, as one might believe.

Comment by Laurent Haan — May 15, 2007

Something wrong with target=”_blank”? Sure you can set some parameters for how the window should look like if you use javascript but for just opening a new window (as for external links and such), I’d rather go with target.

Comment by Andy — May 15, 2007

@Andy the target attribute does not exist in xhtml strict. its only allowed in transitional and is not present in xhtml1.1. check http://www.w3.org/MarkUp/2004/xhtml-faq#target
there is plenty of discussion on the web about why not to use target. just do a search on it and decide for yourself whether you want it.

Comment by Gordon — May 15, 2007

Not quite the one true way. In many cases it’s a good idea to first check if shift, alt, ctrl or meta are being pressed – that way if someone wants to open the link in a new tab they can do it easily. Roger Johansson’s implementation shows how to do this (look at openWin for the callback function).

It can also be a good idea to put the handler on an element containing the links (maybe document.body) and deal the event as it bubbles up.

Comment by Daniel — May 15, 2007

I personally like to use something like onclick=”return openWindow(this)”
where the openWindow() function returns false if the window is succesfully opened. This way popup blockers can sometimes be caught and the link is opened regularly.

Comment by Menno van Slooten — May 15, 2007

“I often wish that links that do rewriting would keep the link for copy and pastability.”

AMEN!

On a related matter: How do I enable the address bar in Firefox in windows that got opened without them, so I can copy the URL? In opera, there is a config option that disallows hiding the address bar and resize controls. I can’t find anything like that in Firefox.

Daniel’s hint on the modifier+click variation is also interesting.

Comment by Martin — May 15, 2007

For more info please visit http://www.businessonmarket.com

Comment by crissec — May 15, 2007

@Laurent Haan: it doesn’t only work with prototype… and why might one think that it adds an onclick event handler to every link on the page?

Comment by chess64 — May 15, 2007

Pretty standard but its amazing how many people ignore this. I hate not being able to middle click and open a link in a new tab because its JavaScript.

Comment by Dougal Matthews — May 15, 2007

@crissec
$$ is a function of prototype, and the reason why it targeting only
one ID is bad, is because if your using pop ups, you will presumably have more than one on a page.

That, along with the dependence on Prototype, makes this snippet a lot less useful than I original thought. Thanks for sharing anyway :]

Comment by alvar — May 15, 2007

Ya, its a little silly to use the ID and then call “each” since there can only be one ID named “#mylink”…

since you know that you can just attach the function directly..


$('mylink').onclick = function(){
window.open(this.href,'name','options');
return false;
};

Ir if you had a bunch of links on the page to add the onclick to than you should be using a class name to locate them all…


$$('a.mylink').each(function(link) {
link.onclick = function(){
window.open(this.href,'name','options');
return false;
};
});

Comment by Alex Duffield — May 15, 2007

Just as an aside, the second bit of code isn’t mine, so I take no responsibility for it =)

Also, a commenter on the post noted a way to get around popup blockers and some IE behaviours, I added some more code at the bottom demonstrating it.

Comment by Ryan — May 15, 2007

Personally I just use Javascript to add somelink.target=”_blank” with Javascript when the DOM loads to any external links. Sure, it’s not allowed in XHTML strict, but it still works and the pages validate. I know I’ll get crucified for this.

Comment by Trevor — May 15, 2007

Nice technique and I’d make one modification to it. Using “this.href” is problematic in IE6 because it will, by default, unescape the URL. You can safely replace it by using this.getAttribute(“href”, 2), which preserves the original URL’s form. Since it’s a JavaScript function, all other browsers ignore the second argument.

Comment by Nicholas — May 15, 2007

If your using jQuery, you might want to check out a plugin called PopUpWindow I wrote that makes writing popupwindows very easy. It even supports profiles. Check it out and any comments or suggestions are welcomed.

http://rip747.wordpress.com/2007/03/02/the-return-of-popupwindow-jquery-plugin/

Comment by tony petruzzi — May 16, 2007

thanks Dion Almaer . it’s working. i have used this in my personal works. thanks. wish you all the best!!!

Comment by Jeevan K Augustin — May 21, 2007

Also, if you are giving the window a name, there is a chance that the window already exists, and might be buried, so I usually check that the window actually opened, and if so give it focus to bring it to the front: var w = window.open(); if (w) w.focus()

Comment by Patrick Fitzgerald — May 22, 2007

Here is the shortcut URL to the Popup window plugin: http://www.shrinkm.com/popup/ I make is for myselft with the free service from http://www.shrinkm.com, but thought others may remember it easier this way.

Comment by james — November 3, 2007

I have a very interesting problem with window.open in javascript. I am using JSF and ajax and if I try multiple launches of my 2nd app, IE freezes and does not even attempt to leave the box. This will happen until I restart my 1st app then a number of tries will work, not always the same, and the window freezes. I verified with HTTP watch to see if it calls out and get dead silence. So I was thinking it is a parent-child window issue so I even have a Active X control that forces an new window to open and I still get it. What the active X does is spawn a new instance of IE that is not a child window. These windows are not related and it still gets hung. BTW The active x does the same as you going to task mgr and starting a new IE task. I’m oit of ideas…..

Comment by Garryc2153 — November 9, 2008

Leave a comment

You must be logged in to post a comment.