How to Show Initials When an Image Is Missing in OrgChart JS
If an employee photo URL is broken, OrgChart JS may display a missing image icon. Instead, you can show employee initials as a clean fallback avatar.
This improves UX and keeps your organizational chart professional.
1️⃣ Handle Broken Images
Add an onerror event to your template image:
function err(image) {
let errImg = image.getAttribute("xlink:href");
let node = nodes.find(({ Photo }) => Photo === errImg);
let circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute("cx", "50");
circle.setAttribute("cy", "60");
circle.setAttribute("r", "41");
circle.setAttribute("fill", "white");
let text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
let initials = node["Employee Name"]
.split(" ")
.map(n => n[0])
.join(".") + ".";
text.innerHTML = initials;
text.setAttribute("x", "25");
text.setAttribute("y", "60");
text.setAttribute("fill", "#039BE5");
text.setAttribute("style", "font-size:24px;");
image.parentNode.appendChild(circle);
image.parentNode.appendChild(text);
}
2️⃣ Update the Template
OrgChart.templates.ula.img_0 = `
<clipPath id="{randId}">
<circle cx="50" cy="60" r="40"></circle>
</clipPath>
<image
onerror="err(this)"
preserveAspectRatio="xMidYMid slice"
clip-path="url(#{randId})"
xlink:href="{val}"
x="10" y="20" width="80" height="80">
</image>`;
Now, when an image is missing in OrgChart JS, initials are displayed automatically.
🔗 Live demo:
Show initials on image errpr