Delicious | Digg | Stumble | Reddit | Float | Subscribe to RSS Feed

search

What I have here is a JavaScript experiment that might be useful.
As we already know, target attribute for anchor tags in strict doctypes is not included. But we also know that sometimes we want to open a page in another window.
If we're talking about all external pages, I might have a solution that you can easily apply even to your old sites.

This script initiates on page load and goes through all links (anchor tags) in the document. It then checks links, and based on current domain name it recognizes them as internal or external. Furthermore, the script adds a class name "external" to all external links. That way you can visually separate them from internal links. The greatest thing about it is that it doesn't demand any markup interventions so you can use them on previous projects by simply plugging in the JavaScript function.

Take a look at the demo | Download Blankwin script

Here's the script. It can't get any simpler.

The script initiates on page load

this.blankwin = function(){
	var hostname = window.location.hostname;
	hostname = hostname.replace("www.","").toLowerCase();
	var a = document.getElementsByTagName("a");	
	this.check = function(obj){
		var href = obj.href.toLowerCase();
		return (href.indexOf("http://")!=-1 && href.indexOf(hostname)==-1) ? true : false;				
	};
	this.set = function(obj){
		obj.target = "_blank";
		obj.className = "external";
	};	
	for (var i=0;i<a.length;i++){
		if(check(a[i])) set(a[i]);
	};		
};

About the author:

cssglobe's image Designer, developer and a passionate standardista with large experience in all types of front-end work. Started to get involved with web in 1999. and turned freelance in 2005., the same year he started Css Globe. Alen's work has been featured on numerous css galleries including famous Css Zen Garden official list. Available for contract work.

Enjoyed the article?

Subscribe to our RSS feed or share it with your friends.

Delicious | Digg | Stumble | Reddit | Float | Subscribe to RSS Feed

Comments

  • Karl Steltenpohl on 7 Feb, 2008 wrote:

    I like. Maybe Ill find a use.
  • Jeremy Hicks on 7 Feb, 2008 wrote:

    Good trick, I've already added it to my arsenal.

    Maybe I don't understand Strict Validation so much, but this script is essentially adding the target="_blank". Is the markup still considered 'strict' once that has been injected?

    And for existing sites, some css backporting might be necessary if you've already styled the links, unless I'm not understanding something.
  • mginop on 7 Feb, 2008 wrote:

    This is great, thanks. I assume if you add class="external" to an internal file (eg: PDF file), it will open in a new tab too?
  • Davewood on 7 Feb, 2008 wrote:

    Isn't this solution cheating the purpose of using strict validation? The idea behind removing the target attribute in the strict doctype is to allow the user to decide when they want to open a new tab/window.

    Rather than using strict validation and this "workaround", why not be truthful and validate it as transitional and use the target attribute.

  • John on 7 Feb, 2008 wrote:

    Looks promising. Will give this a go.
  • cssglobe on 7 Feb, 2008 wrote:

    Well, Davewood you are partially correct. Primarily the idea is to warn user about new window, to let him know that this is going to happen and avoid confusion. On some screen readers there are no telling that this has happened. Those readers generally don't support JavaScript, so there's no harm done with unotrusive JS.
    Btw, even in the working draft for Techniques for WCAG 2.0 there is a sample function
  • cssglobe on 7 Feb, 2008 wrote:

    On the other note, should we use script to maintain valid code and have page behave "invalid"... That is a really good question. Similar thing happen with including source code for flash. Basically what you do is insert invalid code. But, with unobtrusive JavaScript you at least filter some potential problems out.
    This script is merely a demonstration, it gives developers a choice of using new windows for all external links if they want to.
  • CSSnewbie on 7 Feb, 2008 wrote:

    This would also be a useful script to run on non-strict documents, assuming you wanted a quick and easy way to change all of your external links to load in a new window. I like the idea of not having to remember to set the target on every single external link, if this is the behavior I wanted. Good stuff!
  • Paul Sayre on 7 Feb, 2008 wrote:

    I'd have to agree with Davewood. This kinda seems like a trick to get around strict dtd. At first glance, this seems like a really good idea simply because most developers want this action.

    But from a user stand point, I want full control over what is opened in what browser window and when. As a user, I would rather see a link of different color or see an icon rather then have my actions dictated by a developer.

    That said, I really like the script. If you have chosen to get around strict and keep the functionality, this is a great way to do it. Keep up the good work, Alen!
  • cssglobe on 7 Feb, 2008 wrote:

    The one way we can all be happy is to include "open external links in new window" option somewhere on the site when using this script.
    This script is merely the tool, we should find the way to use it in a good way...
    Cssnewbie noticed it well, the of the script "strength" is in its applicability. You can simply drop it on the document and it will work, no interventions in the code needed. How will you deliver that option to users is up to you.
  • kenman on 8 Feb, 2008 wrote:

    A couple notes...

    1) Instead of attaching the script to the global JS object, it'd be better served wrapped in an anonymous structure so as to avoid global namespace collisions.

    2) All modern browsers I believe support the lvl 1 DOM "links" collection, which I would presume would be considerably faster than getElementsByTagName().

    3) You don't need all those this's.

    4) The script WON'T "initiate on page load". It merely gets defined. You'd have to manually call blankwin(), and only sometime after the DOM is loaded.

    My take:

    (function(){
    var hostname = window.location.hostname.replace("www.", "").toLowerCase();
    var i = document.links.length;
    while ( --i >= 0 ) {
    var thisLink = document.links[i];
    var thisHref = thisLink.href.toLowerCase();
    if ( thisHref.indexOf("http://") != -1
    && thisHref.indexOf(hostname) == -1 )
    {
    thisLink.target = '_blank';
    thisLink.className = 'external';
    }
    }
    })();
  • kenman on 8 Feb, 2008 wrote:

    I see now in your demo you have an additional function not shown above, addEvent(). To be clear, the snippet I posted above would only work if place at the bottom of the page, which of course isn't always desirable.

    I would still highly recommend using document.links.length though if your page is anything other than simple.
  • cssglobe on 8 Feb, 2008 wrote:

    Thanks for sharing that, kenman.
  • Mike on 8 Feb, 2008 wrote:

    Wasn't this originally posted in 2003 by Kevin Yank? Reason I know is because I just researched this for a couple hours the other day.

    http://www.sitepoint.com/article/standards-compliant-world
  • cssglobe on 8 Feb, 2008 wrote:

    @Mike: there are lots of examples like Kevin's. The difference between his example and mine is that my script does this automatically.
    It examines the value of the href attribute, compares is to current domain name, and if the domain name is different, it marks link as external. Plus, my script adds a class name on external links, something Kevin's script doesn't do at all. That class name can be used to visually separate external links.
    Downside to Kevin's script is that you have to manually add rel="external" to each anchor tag you want to open in new window. Downside to mine is that you can't separate some external links from others.
  • Mike on 8 Feb, 2008 wrote:

    Ahh..I see. I kind of like the upside's of both. Thank you for clarifying!
  • naveed on 12 Feb, 2008 wrote:

    wow...this is great. I will must use this in my project. I love this! thanks
  • Vincenzo on 15 Feb, 2008 wrote:

    Thanks for wonderful script. This i a good idea to show to users what link are external and also what link will be opened in a new window.
  • track40 on 18 Feb, 2008 wrote:

    Looks like a nice script...

    This seems to work for me, and validates with XHTML Strict:

    http://www.yourdomain.com

    Insert the: onclick="window.open(this.href,'newwin'); return false;" into your <a href>, and the link when clicked will spawn a new window.
  • Vitaly on 19 Feb, 2008 wrote:

    Nice idea! Thanks.
    Bad for SEO :(
  • noth on 21 Feb, 2008 wrote:

    Hola, perdón por no hablar en ingles.

    Yo tengo creado un plugin para jquery que hace eso mismo, y además una serie de funcionalidades más , lo podeís probar y descargar en http://www.noth.es/2007/11/24/actualizacion-del-jquery-link-version-03/

    Demo
    http://www.noth.es/jquery/mis_plugins/jqueryLinks-0-3-by-noth/

    Saludos
  • Faisal on 25 Feb, 2008 wrote:

    i tested the script, it works fine.

    but i have a question, with AdSense ads, will it open in a new window?

    i actually don't want the AdSense ads to open in a new window, because its against google TOS.

    i couldn't test it, because i dont want to click my own ads.

    thanks
  • chad on 29 Feb, 2008 wrote:

    Nice idea..but for SEO purposes what about "nofollow"? Or does this work with it as well?
  • Miller Medeiros on 15 Apr, 2008 wrote:

    very handy script.. the only things i suggest is using [ document.anchors.length ] instead of [ document.getElementsByTagName("a"); ]

    also instead of just setting the className to "external" you should append it.. because if some external link already have a class it will be replaced after the script runs.. it should be [ obj.className += " external"; ]

    i also suggest compressing the javascript and put in the zip file a compressed JS and an uncompressed file (source)..

    thanks for sharing your knowledge with the community, your blog have some very nice tips.. keep your good work..

    cheers..
  • Martin on 16 Apr, 2008 wrote:

    I think this should be an option in the browser (for those people too lazy to move the finger from the left to the middle button).

Post a comment