I’ve seen several examples of automatically loading a Gravatar image on the fly based on an input form field. After coming across another one recently and not finding a Javascript library that would do this for me, I sat down to play with this process a bit. I knew the process wasn’t complex, but at the same time it seemed like something that should have an easy to use drop in module to make it work. The result is a simple jQuery plugin I’m calling form2gravatar.
The source code is available at https://github.com/josephscott/form2gravatar, along with a simple demo at http://josephscott.org/code/javascript/form2gravatar/. To get started you need a form field, and a target image element:
[sourcecode lang=”html”]
<div>
Email <input type="text" name="email" id="email">
</div>
<div>
<img src="http:////www.gravatar.com/avatar/00000000000000000000000000000000?d=mm&s=64" id="gravatar" alt="Gravatar" height="64" width="64">
</div>
[/sourcecode]
Assuming you’ve loaded jQuery and form2gravatar.js you can then trigger a Gravatar image lookup with:
[sourcecode lang=”javascript”]
$( ‘#email’ ).form2gravatar( { target: ‘#gravatar’ } );
[/sourcecode]
This tells form2gravatar to watch the keystrokes in the #email
element and update the #gravatar
image. By default it will check the form value several times a second, which makes it easy to update the image rapidly, but might be a waste in some cases. So there is an option to only do an image update when the form field loses focus (use_blue
).
For pages with several form fields setting use_blur
to true will still provide a good experience and have almost no performance impact on the page. If you only have a few form fields (like on a log in page) I’d stick with the default behavior. You can adjust how frequently the form field is checked with the timer_interval
option.
Here is a list of all the options in form2gravatar:
[sourcecode lang=”javascript”]
var opt = {
‘default_img’ : ‘mm’,
‘size’ : 64,
‘ssl’ : false,
‘target’ : false,
‘timer_interval’: 100,
‘use_blur’ : false
};
[/sourcecode]
The only one that is required is target
. The other option many folks will want look at is default_img
, which by default uses the mystery man from Gravatar. You can use any of the other Gravatar default options (404, mm, identicon, monsterid, wavatar, retro, and blank) along with a URL to some other image.
The Github repo includes a demo.html file that shows this in use for sign in page. From there you can copy and tweak it into what ever shape you’d like.
5 replies on “Automatically Loading a Gravatar Image Based on Form Field Input”
Nice! Now I need to figure out something to use this in.
A log in page is one place I’ve seen it used and is the first place I’d think of.
Yeah, that was my first thought. Might be cool in a contact form, too.
Any place you see an email form field 🙂
What happened to this? Can you please send me files… of course, for purely academic reason.