Tuesday, July 30, 2013

How to Open Links in a New Window Using jQuery

All links will be opened in a new window if u use this Javascript code that use jQuery framework.

$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank');
});
}
});

Or, you can still avoid the validation problems and just append the class target=_blank thing to any links with href attributes starting with http://. The example below only targets links in a #content area. Scoping down like that might be a good idea in case your menus are dynamic and create full URLs.

$("#content a[href^='http://']").attr("target","_blank");


A slightly different version if you only want to target specific URLs (I use the rel tag “external”):

$('A[rel="external"]')
.click( function() {
window.open( $(this).attr('href') );
return false;
});

Also below is a snippet we’re using that works similar to others and add support for target “_blank”, “parent”, “top” and “popup” :

function externallinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i=0; i<anchors.length; i++) {
var anchor = anchors[i];
anchor.tabindex = i;
if (anchor.getAttribute("href")) {
if (anchor.getAttribute("rel") == "external")
anchor.target = "_blank";
else if (anchor.getAttribute("rel") == "parent")
anchor.target = "_parent";
else if (anchor.getAttribute("rel") == "top")
anchor.target = "_top";
else if (anchor.getAttribute("rel") == "popup")
$('a[rel="popup"]').click(function(){return $.dbPopWin( $(this).attr('href'));}
);
}
}
}

If code is garbled, grab it here: http://www.id3.co.th/js/lib.js (look for “links and popups”) 
You then activate it in your pages by adding externallinks(); in your $(document).ready(function(){
If code is garbled, check the source of http://www.id3.co.th/ (look for “.ready(function”)
Disqus Comments