Opening External Links in a New Window Using jQuery
…continued from previous page.
WP Installation
Now that we’ve gotten the script working we’re going to want to install it in our WordPress‐powered site per WP standards. We could make a direct call to the scripts (both the jQuery library and our personal External Link script), but that has the potential to cause some conflict issues with other javascripts.
Fortunately for us, WordPress has two built‐in functions called “wp_register_script” and “wp_enqueue_script()” which give us a safe way to add javascripts to WordPress‐generated pages. I find it easiest to use “wp_register_script” to register any javascript I write and then place a call to it in the <head> section using “wp_enqueue_script()“.
Upload the script
I have a directory in my theme folder labeled “js” for all third-party and personal javascripts. You can either create a directory in your theme folder to upload this script to, or just upload the script into the root of your theme folder. I like keeping my theme folder organized, hence the “js” sub-folder.
You can download the complete script (with comments) here.
You can download the No Conflict version (with comments) of the script here.
Whichever version you choose, save it as “jquery_externalLinks.js” and upload it to your theme folder.
I have a directory in my theme folder labeled “js” for all third-party and personal javascripts. You can either create a directory in your theme folder to upload this script to, or just upload the script into the root of your theme folder. I like keeping my theme folder organized, hence the “js” sub-folder.
Once you’ve uploaded your script, it’s time to register it.
Register the Script
Open your WP “functions.php” file using your favorite text editor (or create one if your installation of WP doesn’t have one) and add the following code:
// This calls the ExternalLink script
wp_register_script(
'jquery_externalLinks',
get_bloginfo('template_url') . '/js/jquery_externalLinks.js',
array('jquery'),
false
);
This tells WordPress the following (in order):
- We’ve installed a new javascript called “
jquery_externalLinks“. - The path to this script is in our template folder in a subfolder called “js”.
- This script requires the jQuery library in order to function.
- There is no version number.
Remember, if you uploaded the script to the root of your theme folder, then you need to change the path to the script.
This:
get_bloginfo('template_url') . '/js/jquery_externalLinks.js',
would become this:
get_bloginfo('template_url') . '/jquery_externalLinks.js',
Once you’ve added this to your “functions.php” file, save the file and upload to your server (or just save, if you’re using the built‐in file editor in the WP Dashboard).
Enqueue the Script
Once we’ve registered the script, we have to tell WP where we want to load it. Since this script is meant to be used site‐wide, we’ll call it in the <head> section of the site with no conditional settings using “wp_enqueue_script()“. Open up your “header.php” file and place the following code in the <head> section before the wp_head() action reference:
<?php wp_enqueue_script( 'jquery_externalLinks' ); ?>
This places a call to load the “jquery_externalLinks.js” file with its dependencies (which are handled by WP since we registered it already).
Since we’ve registered our script already in the “functions.php” file WordPress knows to load the jQuery library before loading our “externalLinks.js” file. Additionally, since we’ve registered all our scripts this way, WordPress will only load the jQuery library once, regardless of how many scripts use it.
Once you’ve entered this code in your “header.php“, save your file and upload to your server. Your ExternalLink script should now be active!
Notes and Resources
- You can download the complete script (with comments) here.
- You can read more about the wp_enqueue_script() function here.
- The article that inspired the whole thing can be found here.
†This is a matter of debate among developers; whether or not utilizing javascript to load the target="_blank" attribute is standards‐compliant. As Kevin Yank states:
The Document Object Model (DOM), which governs the document objects and attributes that are available to JavaScript code, is a totally separate standard from (X)HTML. Also consider that the DOM 2.0 standard that was published in January 2003 (well after XHTML 1.0, let alone HTML 4.0) still includes this attribute. It seems clear that while this attribute is slated to be phased out of (X)HTML, it will be available to JavaScript through the DOM for the foreseeable future.
One drawback to using “window.open(this.href);” is that some browsers do not pass the referring url on to the new window. You can get around this by replacing:
.click( function() {
window.open(this.href);
return false;
});
with:
.attr( 'target', '_blank')
Update
082609: I’ve been contacted by a few people stating the script breaks or doesn’t function properly. I believe this is due to the version of the jQuery library packaged with WordPress. The JQuery library bundled with WordPress starts with the JQuery.noConflict call to prevent conflicts with other javascript libraries (such as Prototype). I won’t go into too much detail in this article, but you can read more about working with jQuery and other libraries here. It’s a little technical, but it basically states that jQuery has a built-in function to make it “play nice” with other libraries.
Because of this, if you’re using plugins on your WordPress installation that use other libraries, jQuery scripts might not work as expected. An easy solution is to create a new variable for the default jQuery $ variable. Like so:
// init a variable for the jQuery noConflict function var $Q = jQuery.noConflict();
The script for opening external links in a new window referenced in this article can be modified like so:
// init a variable for the jQuery noConflict function
var $Q = jQuery.noConflict();
$Q(document).ready(function() {
// find all links that begin with "http://"
$Q('a[href^="http://"]').filter(function(){
// filter out links that have the same domain name as the current page
return this.hostname && this.hostname !== location.hostname; })
// add a CSS class of "external" to each external link (for styling)
.addClass("external")
// inform visitor that link will open in new window
.attr( 'title', 'Link will open in new window')
// open link in new window once clicked
.click( function() {
window.open(this.href);
return false;
});
});
You can download the No Conflict version of the script here.
Conclusion
This script was initially designed because I frequently point visitors to resources/articles located on other sites within the articles I write. I wanted a way for a visitor to stay on my site to continue reading the article, yet still be able to reference the resource I was linking to. Granted, modern browsers have the “open link in new tab/window” feature, but I wanted what amounts to, a hands‐off way of working with these external links. Utilizing the lightweight jQuery library and a very small script, we now have a user‐friendly, developer‐friendly, standards‐compliant way of working with external links. What’s more, this script degrades nicely if the visitor has javascript turned off.
I hope this comes in handy for someone when developing a theme or just for learning purposes. It was designed specifically to handle the external links used on this site, but it should work in most WP installs. I’m always open to feedback, so if you see areas of improvemenet or something I’ve overlooked, just let me know!
Reader Comments
→ Skip to Comment Form
[...] By far, this is probably the slimmest and bug-free code I’ve seen. It’s taken from martinish.com and you can also refer to that site for more details and instructions as [...]
Can you tell me if this also works on links in RSS feeds (inbound). It doesn’t seem to be working for those (or any link for that matter).
I’ve followed the instructions to the letter, but alas, no luck.
Thanks for you work on this script, it’s a great idea!
Beautiful. Works like a charm. Thanks for the script.
You may have another javascript that is incompatible with this script. Or it may not be enqueing properly. Can you see the link to the script in the source code of your header?
Thanks for the script, it works great.
@barry Laminack: it works as well as in post or widget. The problem maybe the name of updated script that we download is jquery_externalLinks.js but on the example on how to put code reference to the header.php is .
Script name with s – jquery_externalLinks.js
Code reference w/o s – jquery_externalLink.js
@Denika: You’re right. I’ve gone ahead and edited the post accordingly. Thanks for picking up on that!