Broken images? Show a placeholder instead

In my recent employee directory app, I had an interesting problem with personnel photos: not everybody had one. Those who did had them stored in a single directory as “{{employee.id}}.jpg”, so it was easy to add a link to the image using AngularJS. But it wasn’t easy for JavaScript to detect if the image was missing or not.

I pondered several possible solutions, and decided on this one: Instead of inline images, which show a “broken image” icon when the image can’t be found, I’d use a fixed-size div element and a style attribute to add the employee’s photo as a background-image. When the employee photo couldn’t be found, the background image would simply be invisible.

To keep this from leaving a hole in my page, I added another div around the employee photo and assigned it a placeholder image. As a secondary benefit, this placeholder would be displayed for every employee in the list until the individual photos had time to load.

HTML:

<div class="outer">
  <div style="background:url(path/to/employee/photo.jpg)"></div>
</div>

CSS:

.outer, .outer > * {
     background-repeat: no-repeat;
    background-size: cover;
    background-position: 50% 50%;
}
.outer {
    background: url(path/to/placeholder/image.jpg);
    width: 200px; /* adjust as needed */
    height: 250px;
}
.outer > * {
    width: 100%;
    height: 100%;
}

See the Pen broken images show placeholder instead by Martin Blase (@mblase75) on CodePen.


Leave a Reply

Your email address will not be published. Required fields are marked *

*