I'm trying to open all external links on the 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.site.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 as much information would be brilliant.
I think I would do it like this:
It's kinda manual but, if you don't want to deal with splitting strings and arrays, this is the solution. I'm sure this will help.
Edit: And addition to this, you can use techfoobar's solution for triggering link clicks. That will help you with your websites performance.
If you'd rather use an event handler on body than change the dom, I recommend something like this...
This will do the trick for all external domains using PHP
Are you able to edit the HTML to get a better hook for maybe a click event? If i need to separate certain links between internal or external i will apply a rel value on the HTML element.
Then in your javascript
EDIT: seeing as you already have a ton of links, how about this..
For triggering the clicks programmatically, you can do something like:
Along the same lines as techfoobar's reply you can build a list of domains that should be left to open in the same window. You can do it in a more robust way though using regular expresions. If you just do a straight indexOf() check you will skip links that have matching subdomains but not matching domains, although you can leave out the '$' if you want to match the name anywhere in the href string.
This implementation should do what you want and there are minimal modifications to the code you have needed.
With this example, all links going to google.com and stackoverflow.com will be left to open in the existing page as well.