Loading gravatar using jquery

前端 未结 4 816
轮回少年
轮回少年 2021-01-31 18:31

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.

How can I do that?

4条回答
  •  生来不讨喜
    2021-01-31 19:00

    The tricky part is generating the URL using an MD5 hash implementation, which is separate from jQuery. I found that the blueimp-md5 library has the most stars of the various MD5 packages on GitHub, and it's pretty much self-contained (about 6kb minified). If you are using Node and/or Browserify, this solution might work well for you:

    var md5 = require("blueimp-md5");
    function gravatar(email){
      var base = "http://www.gravatar.com/avatar/";
      var hash = md5(email.trim().toLowerCase());
      return base + hash;
    }
    

    Then you can set an image src attribute using jQuery like this:

    var email = "someone@example.com";
    $("#image").attr("src", gravatar(email));
    

提交回复
热议问题