Onward and Upward with jQuery: Reworking My External Links JavaScript

I’ve been watching so many folks out there doing cool things with jQuery, and it’s time to bite the bullet and get up to speed.  I wanted to take a look at something I’d recently posted about and see how I could do it with jQuery rather than pure JavaScript to see what the differences might be.  Sort of my own personal “Hello World”.  A good candidate seemed to be my post entitled  External Link Indicator for SharePoint Pages Using JavaScript.  The basic idea is to show a little external link icon whenever a link is going to take to to a different hostname, like this:

image

There’s no real reason to write this from scratch, as there are some good examples out there, such as the one from Karl Swedberg (Quick Tip: Dynamically add an icon for external links) and others.  However, I wanted to try to mirror my earlier implementation exactly, which was a little different in that I used a CSS class to contain the icon reference and the spacing so that I could easily adjust over time, as needed.

So, first of all, I went and grabbed the jQuery code and put the .js file in a Document Library in my test site.  Then I added a reference into my test page:

<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">   
<META Name="CollaborationServer" Content="SharePoint Team Web Site">    
<script type="text/javascript" src="Document Library/jquery-1.3.2.js"></script>    
</asp:Content>

Next I grabbed Karl’s jQuery code and added it after the jQuery reference in my page.  I made adjustments, as follows:

  • Added a new CSS class (ExternalLink) rather than appending the icon directly in the DOM
  • Made sure that the links that are marked are only within the main content table with id=MSO_ContentTable
<asp:Content ContentPlaceHolderId="PlaceHolderAdditionalPageHead" runat="server">   
<META Name="CollaborationServer" Content="SharePoint Team Web Site">    
<script type="text/javascript" src="Document Library/jquery-1.3.2.js"></script>    
<script type="text/javascript">    
$(function() {    
    $('#MSO_ContentTable a').filter(function() {    
        return this.hostname && this.hostname !== location.hostname;    
    }).addClass('ExternalLink');    
</script>    
</asp:Content>

So the jQuery code is definitely smaller and tighter.  I also found it easy to tweak, once I’d skimmed through some of the tutorials.  I think I’ll try reworking a few more of my JavaScript examples when I get a little time.

Similar Posts

3 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.