views:

369

answers:

1

Hi,

Just trying to crate a simple comment form on a blog. I want to load the user's gravatar (using jquery) when he/she writes this in the email box.

Anybody have a good code-snipit?

+6  A: 

The gravatar url looks like this:

http://www.gravatar.com/avatar/<md5hashofemail>

Here are the rest of the options for the URL.

So all you're going to have to do is include a function called md5 that returns the md5 hash of the user's email. There are many online that do this, but I believe this one works well. After that, just do:

// get the email
var email = $('#email').val();
// -- maybe validate the email? 

// create a new image with the src pointing to the user's gravatar
var gravatar = $('<img>').attr({src: 'http://www.gravatar.com/avatar/' + md5(email)});
// append this new image to some div, or whatever
$('#my_whatever').append(gravatar);

// OR, simply modify the source of an image already on the page
$('#image').attr('src', 'http://www.gravatar.com/avatar/' + md5(email));

I thought this was obvious, but I will add it for posterity's sake:

If user emails are private and you're showing this ala-stackoverflow in a listing, you are probably better off encoding the email on the server so that user emails are not publicly visible if you look at the source.

Paolo Bergantino
I'll save you a google search: http://www.webtoolkit.info/javascript-md5.html
DrJokepu
so there is a problem with using javascript to load gravatars, because it not a good idea to output your users email and md5 hash clientside
Sander Versluys
@Sander Versluys: There aren't problems if you just load it from textbox as the user enters his/her email.
Mehrdad Afshari
@Paolo - as @Mehrdad says, no problem if u are generating the has from an email entered into a textbox by the user. bigger problem if you are using this to display gravatars on a publicly visible page. i.e. if a forum used this to display gravatars beside posts - u could view source and see everyones email addresses.
russau
Cheers, this just saved me a load of Googling. Using it to preview the Gravatar on a sign up form.
Colonel Sponsz