Quick & Dirty: Change email addresses in Gravatar icons with jQuery
Warming up this morning with a code snippet: we want to change the mailto: link in a gravatar enabled link using jQuery. First of all surf to http://en.gravatar.com/site/implement/url to understand how the gravatar link is formed. So we need ad md5 of our email addresses, just go to http://www.semnanweb.com/jquery-plugin/md5.html and download the MD5 plugin for jquery.
All we need to do is just find all the mailto link using a simple selector $('a[href^=\"mailto\"]') and then manipulate the content.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Gravatar demo</title>
<script type="text/javascript" src="jquery-1.3.2-vsdoc.js"></script>
<script type="text/javascript" src="jquery.md5.js"></script>
<script type="text/javascript">
function unescapeEmailAddress(email) {
return email
.replace(new RegExp(" !dot! ", "g"), ".")
.replace(new RegExp(" !at! ", "g"), "@")
.replace('mailto:', '');
}
$(function() {
$('a[href^=\"mailto\"]').each(function() {
var self = $(this);
var email = unescapeEmailAddress(self.attr('href'));
var md5 = $.md5(email);
var gravatar = 'http://www.gravatar.com/avatar/' + md5 +'?d=monsterid';
self
.html('<img src=\'' + gravatar + '\' alt=\'' + email + '\'/>')
.attr('href', 'mailto:'+email)
;
});
});
</script>
</head>
<body>
<a href="mailto:mtb !dot! snowboard !at! gmail !dot! com">mtb !dot! snowboard !at! gmail !dot! com</a>
<a href="mailto:prova !at! prova !dot! com">prova !at! prova !dot! com</a>
</body>
</html>