Techblog Index

Quick Tip: Do you miss the target?

Opening links in a new window was once quick and easy but since the target="_blank" options on a links have died (if you didn’t knew, I’m very sorry to be the one telling you this) the only way left was the javascript way.

The click event on a link cannot be anymore traced by the onclick parameter on the a tag because all the on* events have died too (I know, it’s a massacre!) so I’ll take this example for basis.

We’ll use JQuery‘s selectors to get the links we want.

All external links

UPDATED: As WordPress makes all links absolute this code got useless. I’ve updated it now to check additionally if the link does not starts with the current domain. I’ve tested it and it worked!

NOTE: I’ve searched for a shorter form where starts-with and negation could be applied together. If someone has a better solution, please share!

$(document).ready(function() {
    var domain = window.location.host;
 
    $("a[href^='http://']").not("[href^='http://"+domain+"']").click(function(ev){
        ev.preventDefault();
        window.open(this.href);
    });
});

All links from a div with ‘#id_div’ id attribute

$(document).ready(function() {
    $('div#id_div a').bind('click',function(ev) {
        ev.preventDefault();
        window.open(this.href);
    }
    );
});

NOTE: I’m using ev.preventDefault() rather than return false to follow JQuery pattern. Just a good practice.
NOTE: ev is just a variable name I gave. You may change it to suit your needs.

Any more ideas?

 
 

Reader's thoughts on "Quick Tip: Do you miss the target?"

1
  1. That’s how I use it too. This is one of the most usual errors I see people do.

    I’m continually amazed how sweet jQuery is to work with. It makes it easy as pie to deal with things like this.

Leave a Reply