Retrieving Gravatar using jQuery

If you have an account with Wordpress or Github, you might have seen them requesting you to setup your Gravatar image so that they can associate it with your account. You can easily set one up and it gets associated to your email address. Now multiple services can choose to simply choose to use your email address to show your Gravatar when you specify your email address, for example when you are providing your email address to submit comments. In this example we will see how we can retrieve the Gravatar for a given email address and use it in our custom applications.

Retrieving a Gravatar

Given an email address, retrieving a Gravatar is quite simple. You have to calculate the MD5 hash of the lowercase and trimmed email address. Once you have the hash, you append it to the URL - http://www.gravatar.com/avatar/<the calculated hash>.

Now you can use this URL in an image tag to show the image.

The default image size returned is 80x80 px. You can specify sizes from 1px to 512px. Depending on original resolution of the image, bigger sizes may get pixelated. To specify size, you pass the query string s=<size> e.g. s=100. So a request URL would be http://www.gravatar.com/avatar/<the calculated hash>?s=100

By default gravatar.com will return the default image hxxp://www.gravatar.com/avatar/00000000000000000000000000000000

If we want we can specify our own image using the query parameter d=<escaped http url of default image>

Creating a Simple Contact List and Retrieving Gravatar

We will create a simple Contact List sample and see how we can use the Gravatar feature.

Step 1: We start off with a default ASP.NET MVC basic template application. If you are not an ASP.NET developer, you can ignore the ASP.NET part and do all of this in an HTML page itself. There is no server side code involved.

Step 2: We add a button that will invoke a input dialog to take a new contact detail

add-contact

Step 3: We add the contact details markup in the Index.cshtml as follows

add-contact-popup

This has three fields that take the Name, Address and Email. In a real life application, we could ask for more parameters.

Step 4: This will be a popup that will be triggered from the ‘Click to Add Contact’ button. We will use jquery-ui’s Dialog plugin to render the inputs in a dialog. The outmost div acts as the dialog container.

We add a javascript file – gravatar-sample.js to the project and setup the dialog as follows

$(function () {
    $("#addContactPopup").hide();
    $(document).on("click", "#addNew", function () {   
        $("#addContactPopup").dialog({
            minWidth: 400,
            width: 500,
            maxWidth: 600,
            title: "Add New Contact",
            buttons: [
                {
                    text: "Add",
                    click: function () {
                        var user = {
                            "Name": $("#nameText").val(),
                            "Address": $("#addressText").val(),
                            "Email": $("#emailText").val()
                        };
                        contactAdd(user);
                        $("#nameText").val('');
                        $("#addressText").val('');
                        $("#emailText").val('')
                        $(this).dialog("close");
                    }
                },
                {
                    text: "Cancel",
                    click: function () {
                        $(this).dialog("close");
                    }
                }]
        });
});

The $(function () {}); is the jQuery shortcut for document.ready.

- Once the document is ready, we hide the ‘add container’ div (id=addContactPopup).

- Next we hook up the ‘click’ event of the ‘addNew’ button.

- In the handler function, we setup the ‘addContactPopup’ div to be used in a jQuery dialog. We specify a bunch of parameters for the height, width, title and buttons. For the buttons we also define a click event handler.

o Add click: When the user provides the contact information and hits Add, the click event handler fires.

  • It creates a user object with three properties Name, Address and Email.
  • Calls the contactAdd method to render the new contact
  • Clears out the input boxes
  • Closes the dialog

o The Cancel click event handler simply closes the dialog

contact-as-method

Step 5: We implement the contactAdd method that takes the newly added User and adds it to the Contact List on screen.

- We first pick out the <ul> element inside which we will be adding the list items.

- Next we call the calculateGravatar method to generate the Gravatar url for use from the email address.

- Finally we use the prepend method to add a list item to the contact list. We format the element inline. Ideally we could use a templating engine like Knockout or jsRender.

Step 6: Calculating the MD5 hash for the Gravatar URL

Calculation of the MD5 hash, is achieved via the excellent Crypto library by Jeff Mott at http://code.google.com/p/crypto-js/

calculate-gravatar

It is an extensive JavaScript library for hashing and encryption. You can download the entire library and from the rollup folder just pick the md5.js. It is a self-contained MD5 hashing implementation.

In the above code, we make sure the email address passed is all lower case and has no leading or trailing spaces. We use the toLowerCase() and trim() methods.

Generating the hash is just a single line call that takes the email as input and returns the hash. The Gravatar url is then create by appending the hash to the URL and ending it off with .jpg so that we can use it in the image tag directly.

Putting it all together

With all in place, we can now build our contact list with Gravatar.

- Click on the ‘Click to Add Contact’ button to bring up the New Dialog.

- Provide the details and click on Add

contact-list-add-new

- The Gravatar takes a second or two to come through and the new contact is added before the existing name in the list.

contact-list-two-people

- We add one more contact and the list wraps around.

contact-list-final

There we go, the who’s-who of .NET community (okay, okay I am kidding myself about that third dude at the bottom ;-)…)

Conclusion

When creating a contacts app or a blog app with comments, it is cool to have the Gravatar of the person show up. In small ways it verifies the person and if they are using a real picture gives a face to a name. With this little utility you can now add this extra polish to your overall Web Application.

The code is on github for your reference, here. You can download the zip, here.

Reference

http://en.gravatar.com/site/implement/

Note: Gravatars of Ayende Rahien and Scott Hanselman used with permission.

No comments:

Post a Comment