Mvied Development

  • Home
  • Blog
  • Portfolio
  • Projects
    • WordPress HTTPS
  • Contact

Unobtrusive Open Link in New Window

10-02-2008 1

As many of you know by now, the attribute ‘target’ will not validate in an XHTML document. This creates quite a few problems for us because we don’t always want people leaving our site entirely. With a simple JavaScript code you can easily open external links in new windows unobtrusively!

First, make a link with the class ‘external’.

<a class="external" href="http://www.mvied.com/">MVied Designs</a>

Now apply this to an external JavaScript file named external.js and upload somewhere on your site.

function init() {
 var links = document.getElementsByTagName('a');
 for (var i=0;i < links.length;i++) {
  if (links[i].className == 'external') {
   links[i].onclick = function() {
    window.open(this.href);
    return false;
   };
  }
 }
}
 
if(document.childNodes) {
 window.onload = init;
}

And link to this javascript in your header with a script tag. Don’t forget to change the location of the javascript file to where you uploaded external.js.

<script type="text/javascript" src="http://example.com/js/external.js"></script>

Responses to “Unobtrusive Open Link in New Window”

  1. windows 7 tweak 03-3-2010 at 8:34 am

    Many thanks for your valuable information. I have been seeking for this for ages in many sites. Windows 7 is a great software ever. I recommend Win7Zilla to tweak Windows 7 effective

Leave a reply

    • Need a professional website for your personal blog or business? I can help with that.

      Get in touch

      About me

      My name is Mike Ems. I'm a professional web developer residing in Louisiana's Northshore.

      I have been working in the web industry for approximately 8 years. I am deeply passionate about the work I do and take pride in every line of code I write.

      more about me
Proudly powered by WordPress | Sitemap | © 2012 Mvied Development