Saturday, June 29, 2013

How to Highlight External Links & Make Them Open In New Windows

You can highlight external links on your blog or website fairly easily. All you need is a small jQuery script and an even smaller CSS code snippet. And you don't even have to go back and edit your existing posts/pages for it to work.

You can also force those links to open in new windows or tabs if you want to.

Here's how:


1. Tag external links

This simple jQuery script will scan your page for external links (links pointing to different domains/subdomains) and assign them with "external" class name. This script excludes linked images because you don't want them to be highlighted. (Images for Blogger blogs are considered external since they are hosted on blogspot subdomains, other than your blog's domain/subdomain).
  1. If you haven't already added a jQuery library call to your template before, copy the code below and paste it above the </head> tag in your template.
    1<scriptsrc='http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js'type='text/javascript'/>
  2. Then add this script before the </body> tag.
    1<script>
    2//<![CDATA[
    3(function($) {
    4$('a:not(:has(img))').filter(function() { return this.hostname && this.hostname !== location.hostname; }).addClass("external");
    5})(jQuery);
    6//]]>
    7</script>


2. Highlight external links

external link symbol iconNow that you've added "external" class to all external links, you can easily target (to highlight) them in CSS using "a.external" selector.
On Blogger, go to Template > Customize > Advanced > Add CSS, add the following CSS code and press the Enter key on your keyboard.
  • For a simple highlight, you can just change the text or background color, like in this example:
    1a.external {color:redbackground:yellow;}
  • Or if you want to use a symbol/icon next to the link, like on Wikipedia and Twitter Developers Site, add the following CSS snippet:
    1a.external {background:url("http://3.bp.blogspot.com/-DXJ-d748UZA/UbVbb7pWlKI/AAAAAAAAEiU/zDhsxdTtXRU/s320/Icon_External_Link+12.png")no-repeat right centerpadding-right:13pxdisplay:inline-block !important; }
    To use a different icon, simply replace the background URL with that of your icon. You can download free external link icons from Shapes4free.


3. Open external links in new windows

You can make the external links open in new tabs or windows, simply by addingtarget="_blank" attribute to the anchor tags. This can be achieved by altering the original script slightly, like this:
1<script>
2//<![CDATA[
3(function($) {
4$('a:not(:has(img))').filter(function() { return this.hostname && this.hostname !== location.hostname; }).addClass("external").attr('target', '_blank');
5})(jQuery);
6//]]>
7</script>
Super easy, right?
Enjoy!
Follow InfotechArena on Twitter @InfotechArena and Facebook

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

ShareThis