Jun 16 2009

This link will take you away

Category: Tips and TricksJoeGeeky @ 11:26

You have probably seen links that indicate whether or not you are leaving a site.  This is certainly not a new pattern, but I still see people writing a bunch of code-behind and user controls to do something that is pretty straight-forward using other patterns. The simplest method is to use Cascading Style Sheet (CSS). Lets walk-through an example.  Here is a picture of what we are trying to accomplish.      

Here is the markup used to accomplish this:

<html>
<head>
  <style type="text/css">
    a[href^="http"] {
      background: url('http://www.smelser.net/externallink.png') no-repeat right top;
      padding-right: 13px;
    }
    a[href^=http://www.smelser.net], a[href^=https://www.smelser.net] {
      background-image: none;
      padding-right: 0;
    }
  </style>
</head>
<body>
  <a href="http://www.smelser.net/Sample.html">This link should <strong>NOT</strong> be external (e.g. smelser.net)</a>
  <br />
  <br />
  <a href="http://www.google.com">This link is an external (e.g. google.com)</a>
</body>
</html>

If you look at the style there are two things happening. The first thing we do is set all links to have the external link background image (e.g. externallink.png). Basically we apply a background to all anchor tags (e.g. <a>) with an attribute starting with http. You can use other attribute selector patterns, if you can meet all your requirements, but the starts-with selector (e.g. ^=) will suite this sample.


  a[href^="http"] { 
    background: url('http://www.smelser.net/externallink.png') no-repeat right top; 
    padding-right: 13px; 
  }

Next we remove the background from all links that start with a URL that is considered internal.  This should include each supported protcol type such as http and/or https, fully qualified domain name, host name variations, IP Addresses, etc.


  a[href^=http://www.smelser.net], a[href^=https://www.smelser.net]{ 
    background-image: none; 
    padding-right: 0; 
  }

That's all you need to do. There are several other extensions you can apply such as including the mailto protocol covering all Email address links. If you do this, you will need to alter the CSS attribute selector to match on the end of the Email address.


  a[href$="@smelser.net"]{ 
    background-image: none; 
    padding-right: 0; 
  }
 

Tags: