Automatically open external links in a new window
Sometimes we want to open all external links in a new window so that our visitors can still staying in our website when visiting the external links. We can manually add [html]target="_blank"[/html] to each link but it’s tons of repeated work to apply to each link. Through this tutorial, you can make this happen with a couple lines of jQuery.
1. Find all external links:
[js]
$(document).ready(){
$("a[href*=’http://’]:not([href*=’"+location.hostname+"’]),[href*=’https://’]:not([href*=’"+location.hostname+"’])");
}
[/js]
2. Add ‘external’ class to all external links:
[js]
$(document).ready(){
$("a[href*=’http://’]:not([href*=’"+location.hostname+"’]),[href*=’https://’]:not([href*=’"+location.hostname+"’])")
.addClass("external");
}
[/js]
3. Open all external links in a new window:
[js]
$(document).ready(){
$("a[href*=’http://’]:not([href*=’"+location.hostname+"’]),[href*=’https://’]:not([href*=’"+location.hostname+"’])")
.addClass("external")
.attr("target","_blank");
}
[/js]
Done.


















