Highlight to the root on search
When implementing search in an organizational chart, a common requirement is to focus on the selected node and its direct lineage while hiding everything else.
With OrgChart JS, this is easy using the searchclick event.
Goal
On search result click:
- Highlight the searched node
- Show only its parent nodes
- Hide all unrelated children and branches
HTML
html
<script src="https://balkan.app/js/OrgChart.js"></script>
<div id="tree"></div>JavaScript
javascript
let chart = new OrgChart(document.getElementById("tree"), {
template: "olivia",
mode: "dark",
nodeBinding: {
field_0: "name",
field_1: "title",
img_0: "img"
}
});
// Customize search click behavior
chart.searchUI.on("searchclick", function (sender, args) {
sender.instance.center(args.nodeId, {
parentState: OrgChart.COLLAPSE_PARENT_NEIGHBORS,
childrenState: OrgChart.COLLAPSE_SUB_CHILDRENS
});
return false; // Prevent default behavior
});
// Sample data
chart.load([
{ id: "1", name: "Jack Hill", title: "Chairman and CEO", img: "https://cdn.balkan.app/shared/1.jpg" },
{ id: "2", pid: "1", name: "Lexie Cole", title: "QA Lead", img: "https://cdn.balkan.app/shared/2.jpg" },
{ id: "3", pid: "1", name: "Janae Barrett", title: "Technical Director", img: "https://cdn.balkan.app/shared/3.jpg" },
{ id: "4", pid: "2", name: "Aaliyah Webb", title: "Manager", img: "https://cdn.balkan.app/shared/4.jpg" },
{ id: "5", pid: "2", name: "Elliot Ross", title: "QA", img: "https://cdn.balkan.app/shared/5.jpg" },
{ id: "6", pid: "3", name: "Anahi Gordon", title: "QA", img: "https://cdn.balkan.app/shared/6.jpg" },
{ id: "7", pid: "3", name: "Knox Macias", title: "QA", img: "https://cdn.balkan.app/shared/7.jpg" },
{ id: "8", pid: "4", name: "Nash Ingram", title: ".NET Team Lead", img: "https://cdn.balkan.app/shared/8.jpg" },
{ id: "9", pid: "4", name: "Sage Barnett", title: "JS Team Lead", img: "https://cdn.balkan.app/shared/9.jpg" }
]);Explanation
The key behavior is inside center:
parentState: OrgChart.COLLAPSE_PARENT_NEIGHBORSkeeps only the path to the root expanded.childrenState: OrgChart.COLLAPSE_SUB_CHILDRENShides descendants and unrelated branches.
This creates a clean and focused view, so users can understand the selected result in its organizational context.