Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

HTML

justinw
justinw
14,517 Points

Initials for Avatar

I've seen a lot of websites like Uberconference, Visual Studio TFS, Skype, Pipedrive, etc that when you create an account for the first time and you haven't uploaded a Profile photo (headshot) it uses your first initial of first and last name.

Does anyone have an idea where to grab this API or is it custom logic?

1 Answer

I don't know if there is such an API, but this can be done in various ways. You can do it both on the frontend or the backend. For instance, in PHP, you could use the GD library to check for the existence of the user image, and if it doesn't exist, generate one with GD so that it contains the initial, and serve that newly generated image instead of the profile photo.

On the frontend side, let's say you're retrieving user data as a JSON. Once you parse the JSON, you'll have an object which could look like this:

var user = {
    username: "jwitz",
    name: "Justin Witz",
    photo: "/path/to/photo" // or an empty string if there is no photo
}

In this scenario, you can check user.photo and if it's an empty string, you'd populate the div (or whatever element) reserved for the profile photo with a specially styled element that displays the initial and set its innerHTML to user.name[0];

Or you could use a canvas element and "draw" the letter on the canvas, followed by the image over it, if it exists.

If the user images are served from a predefined uniform url (like user/username/photo) you can even use an XMLHttpRequest to check if the image exists or the path returns a 404 in which case you'll apply the first letter of the name or surname.

If you use jQuery, something like this could work:

$.get('user/' + user.username + '/photo')
.done(function() { 
    // add the image to the DOM
}).fail(function() { 
    // add the specially styled element and set its text to the first letter of the name
});

I hope this helps, or at least gives you a general idea about how it can be done.