Get Started! Locating External Links
Here's how to find external links on the page, using JavaScript & then adding an icon & forcing it to open in a new window.
Find External Links
Using jQuery we can find all the a
/ links and using the .filter
property test the .hostname
property of the link against document.location.hostname
, For example :
var $exts = $('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
});
This will match all external links on the page. If you wanted to only match links found within given area you could use this following :
var $scpoe = $('.scope');
var $exts = $scope.find('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
});
Another issue maybe that you only want to locate elements which are not a descendant of some other elements within the $scope
.
var $exts = $scope.find('a').filter(function() {
return (this.hostname && this.hostname !== location.hostname) && (
$(this).closest('.some-class').length <= 0
)
});
This will only match elements that don't have a parent / ancestor with the css class some-class
.
Add Class to External Links
We can now alter these links, adding a class & altering the target
, forcing this link to open a new window or tab:
$exts
.addClass("external")
.attr('target', '_blank');
Add icon to external links
As font-awesome is included with .dash
I use the following CSS to render an icon after
the link :
a.external {
&:after {
font-family:FontAwesome;
content:"\f14c";
}
}
If you wanted to place the icon before
the use :before
instead of :after
.
Why "\f14c"
?
This is the unicode value for the icon, this can be found on the Font Awesome external link icon page.
Adjust the position of external link icon
I normally include a minor positional adjustment to fit the icon inline a little better :
a.external {
&:after {
font-family:FontAwesome;
content:"\f14c";
position:relative;
left:3px;
margin-right:2px;
}
}
Example of External Link with Icon
This Link to the NetCanvas.io site which is external to this site will cause the icon to be rendered and when clicked the page will be opened in a new tab.