Determine if gravatar return default image using javascript
Asked Answered
M

1

6
var gravatar1;
var gravatar2;
var email1 = $(email1).val();
email1 = $.trim(email1);
email1 = email1.toLowerCase();
email1 = md5(email1);
gravatar1 = 'http://www.gravatar.com/avatar/' + email1;
var email2 = $(email2).val();
email2 = $.trim(email2);
email2 = email2.toLowerCase();
email2 = md5(email2);
gravatar2 = 'http://www.gravatar.com/avatar/' + email2;

is there any way to determine if gravatar1 returns the default image so that i can override gravatar1 to display gravatar2 image. gravatar2 only overrides gravatar1 if the default image is returned. Thanks!

Marjorie answered 10/9, 2015 at 6:36 Comment(0)
P
16

If you add a d=404 to the url gravatar will return a 404 status instead of a default image if the user does not have an image set.

i.e. http://www.gravatar.com/avatar/098f6bcd4621d373cade4e832627b4f6?s=80&d=404 (user image not available)

Will return a 404.

While

http://www.gravatar.com/avatar/c9ef50b85bd345ea4e0d8da558816f3d?s=80&d=404 (user image available)

Will return the image.

So you can do the below, which basically iterates through all img.gravatar-img elements, gets the src, sets the d=404 mentioned above, then sends a request(type:HEAD) for the src,

if the page returns a 404, the error block will run allowing you to replace the src of the image with one available, i personally have the default image on the image i.e

<img src="" data-defaultImg="">

or the other way around - you can set the src to the default image replace the error block with a success block, thus if the gravatar image exists replace the default image, this prevents showing a "not found" image on the page if JS is disabled or if the ajax call takes time.

$("img.gravatar-img").each(function(i,el) {
imgUrl = $(el).attr("src") + "&d=404";

// Image Does Not Exist
  $.ajax({
    url:imgUrl,
    type:"HEAD",
    crossDomain:true,
    error:function(){
      $(el).attr("src", $(el).attr("data-defaultimg"));
    }
  });
});
Pyriform answered 18/9, 2015 at 15:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.