Use jQuery to Decorate Links

I’ve recently been in the habit of decorating links to Twitter profiles with the Twitter icon. This technique makes it easy for readers to scan a page and know exactly where the link points without having to spend time hovering over or clicking on the link.

After creating the code for this a few times manually, I decided it was time to come up with something a bit more elegant. My enduring love for jQuery proved useful once again. The following code is just a few lines of jQuery code to add the Twitter icon to each Twitter link on the page.

<style type="text/css">
.twitter-link
{
     background-image:url(images/icons/fav-twitter.png);
     background-repeat:no-repeat;
     padding-left:20px;
}
</style>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
     $(document).ready(function() {
         $("a").each(function() {
             if ($(this).attr("href").toLowerCase().indexOf("http://twitter.com") != -1) {
                 $(this).addClass("twitter-link");
             }
         })
     });
</script>

...

<p><a href="http://twitter.com/craigshoemaker">craigshoemaker</a></p>

Check out this working example

Obviously the uses for this approach don’t stop at Twitter. I first started using this technique for creating links to PDFs (which gives the user a heads up they may want to go walk the dog while they wait for their PDF reader to load).

What other uses do you see here?

Update 4/16/2009:

Fredrik Vig suggested in the comments the following much more elegant approach:

$("a[href^='http://twitter.com']").addClass("twitter-link");

Read the ^ like: target all links that start with http://twitter.com.

Published Friday, April 10, 2009 1:55 PM by craigshoemaker
Filed under:

Comments

# re: Use jQuery to Decorate Links

Monday, April 13, 2009 1:45 PM by Veera

The same technique can be used to add icons to links (such a PDF or Word/Excel document).

# re: Use jQuery to Decorate Links

Monday, April 13, 2009 1:51 PM by craigshoemaker

@Frederik very nice! thanks for sharing

# re: Use jQuery to Decorate Links

Wednesday, April 15, 2009 9:19 PM by Chris Marin

Can I get credit for introducing you to jQuery? :)

# re: Use jQuery to Decorate Links

Thursday, April 16, 2009 8:46 AM by craigshoemaker

@Chris: Absolutely!

Craig