How to create a warning when opening external links in jQuery

Posted Aug 9, 2012 | ~2 minute read
WARNING : This post contains an obscene amount of sarcasm.

Working in a regulated industry has it's complications, and some of these are created by over-zealous compliance teams who assume that every web visitor has the IQ of a peanut.

Let's face it, visitors on the web know when they click a link to another site that the original site they were looking at has no authority over the content shown on the new site, right? It's one of the quickest things you'll probably learn when browsing the web, yet some compliance teams think otherwise and will insist you warn your visitors when clicking an external link. Yay for them!

If you hit this snag, the following code should do everything you need. It'll automagically check every link on your site to see if it links to an external site or your own. If it's an external link, it'll fire off a pop-up confirmation box that shows the warning, and has an "ok" or "cancel" button. If the user hits "ok", it'll redirect them to the site they wanted to visit in the first place. If they hit cancel, it'll keep them on the page. Simples.

If you're not proficient with javascript or jQuery, your web developer should make perfect sense of this :


var root = new RegExp(;


        // a link that does not contain the current host
        var url = $(this).attr('href');
        if(url.length > 1)

$('a.external').live('click', function(e){

    var answer = confirm("You are about to leave the website of [COMPANY NAME] and view the content of an external website. [COMPANY NAME] cannot be held responsible for the content of external websites.");

    if (answer){
        window.location = $(this).attr('href');



Now your compliance team can sleep happy at night knowing that if a peanut visits your site, they'll know whether it's your site or another they're looking at! Phew!

If you need a hand installing this on your own site, shout!