Using JQuery To Open External Links In A New Window
Published by philipnorton42 on Fri, 02/19/2010 - 10:17Opening external links in a new window can be useful, but adding target="_blank" can be a real chore. Not only that, but if you are trying to validate the page to XHTML strict then the target attribute will cause errors to appear as it is not defined in XHTML.
An easy solution to this issue is to add the following JQuery to your site. It will look for any links that start with http and do not contain the current domain and add a new click event to them that causes a new window to be opened. This will exclude most links straight away as they will most likely be relative.
1 2 3 4 | $("a[href^='http']:not([href*='example.com'])").click(function(){
window.open(this.href);
return false;
}).attr("title", "Opens in a new window"); |
This code will also add a new title to each link, replacing any that already exist, just remove the call to attr() at the end of the block to stop this. If you are using this on your site then make sure you put this into a dom ready block, and also that you change the example.com to be your own domain name.
Comments
Using JQuery To Open External Links In A New Window
Anonymous (not verified) - Mon, 10/11/2010 - 18:52This is a pretty good
philipnorton42 - Mon, 10/11/2010 - 21:38This is a pretty good resource:
Window open() Method
So, in adapting the above snippet you would get:
$("a[href^='http']:not([href*='example.com'])").click(function(){ window.open(this.href,'','width=200,height=100'); return false; }).attr("title", "Opens in a new window");Great. Here are a couple tweeks.
Unseen Revolution (not verified) - Thu, 09/22/2011 - 23:21I like to use the following:
$("a[href*='http://']:not([href*='"+location.hostname.replace("www.","")+"'])").each(function() { //do some 'stuff' to the external link });I also like to add an external class to the link for styling and also use:
$(this).click(function(event) { window.open(this.href, '_blank'); });Full code and examples at:
jquery external links in new window
it seems better to write:
Alireza (not verified) - Mon, 10/03/2011 - 06:38thanks
mojgan (not verified) - Sat, 12/31/2011 - 09:04thank u very muchhhhhhhh
it's help me
Add new comment