Open All External Links in a New Browser Window
Expanding on the post about XHTML valid target post.
Lets make this a bit automated using jQuery to search for external links and add a class named external.
As before, these links will be XHTML valid.
Then from the post we are expanding on these links will be automatically opened in a new window.
To start we need to load jQuery in our site, quick and simple we will load it from Google.
1 |
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> |
Moving on to the code needed for our task,
The Full Code, I will explain following the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
jQuery(document).ready(function(){ //Process links to check if they are internal or external var start = "[href*='"; var local = 'http://localhost/'; var urlcheck = start + local + "']"; jQuery("a[href^='http:']").not(urlcheck).addClass('external'); //External links should now have a class added to them, lets process this classes action jQuery(function(){ jQuery('a.external').click(function(){ window.open(this.href); return false; }); }); }); |
The line that MUST BE CHANGED
1 |
var local = 'http://localhost/'; |
The http://localhost/ needs to be changed to the URL of your site.
For example, here it would be http://validwebs.com/
It gets added to the urlcheck variable and used for checking all links against with in the viewed page.
Then the search happens in this line
1 |
jQuery("a[href^='http:']").not(urlcheck).addClass('external'); |
If any links in the page do not have the URL var local
they will have the external class added to them.
Then the click function is added to the class external the same as in the original post.
1 2 3 4 5 6 |
jQuery(function(){ jQuery('a.external').click(function(){ window.open(this.href); return false; }); }); |
From that point on all external links with in the site will open in a new browser window.