Javascript: Open a Link in a New Window

As you know, in XHTML, you can't use the target="_new" attribute to open a new window. This short javascript solves the problem. The script was found in HTML Mastery Semantics Standards and Styling.

Apply this code to your HEAD part of your document:

  • <script type="text/javascript">
  • function popup()
  • {
  • if (document.getElementsByTagName) {
  • a = document.getElementsByTagName("a");
  • for(i=0; i<a.length; i++)
  • {
  • if(a[i].getAttribute("rel")
  • && a[i].getAttribute("rel") == "external")
  • {
  • a[i].onclick = function()
  • {
  • window.open(this.getAttribute('href'));
  • return false;
  • }
  • }
  • }
  • }
  • else return false;
  • }
  • window.onload = popup;
  • </script>

Then use this piece of code to activate it:

  • <a href="http://whatever.com" rel="external">This is a link</a>
eXTReMe Tracker