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.