Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
35
rated 0 times [  37] [ 2]  / answers: 1 / hits: 16753  / 12 Years ago, wed, august 22, 2012, 12:00:00

I'm trying to open all external links on a site in a new window. However on there are 2 versions of the site, e.g. a store and the main site. So on the main site we might have links that go to http://store.example.com for example.



I've got some code here which will allow me to open all the external links in a new window. However I'd like to be able to exclude certain domains. Like the one I've mentioned above.



Here is the code:



$(document).ready(function() {
$(a[href^=http]).each(function(){
if(this.href.indexOf(location.hostname) == -1) {
$(this).attr({
target: _blank,
title: Opens in a new window
});
}
})
});


I'm new to JS / jQuery so any additional information would be brilliant.


More From » jquery

 Answers
29

For triggering the clicks programmatically, you can do something like:



$(document).ready(function() {

$(a[href^=http]).each(function(){

// NEW - excluded domains list
var excludes = [
'excludeddomain1.com',
'excludeddomain2.com',
'excluded.subdomain.com'
];
for(i=0; i<excludes.length; i++) {
if(this.href.indexOf(excludes[i]) != -1) {
return true; // continue each() with next link
}
}

if(this.href.indexOf(location.hostname) == -1) {

// attach a do-nothing event handler to ensure we can 'trigger' a click on this link
$(this).click(function() { return true; });

$(this).attr({
target: _blank,
title: Opens in a new window
});

$(this).click(); // trigger it
}
})
});

[#83488] Tuesday, August 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarvisjovannia

Total Points: 127
Total Questions: 123
Total Answers: 101

Location: Netherlands
Member since Mon, Jun 7, 2021
3 Years ago
;