How to Implement Click Handlers on Nodes in Mermaid Diagrams
To implement click handlers on Mermaid diagram nodes, declare a click directive in your diagram syntax that references a globally reachable JavaScript function, which the SVG renderer automatically binds to the generated node element during the rendering pipeline.
The mermaid-js/mermaid repository provides a native event system that transforms static diagrams into interactive visualizations. By parsing click directives during diagram processing and attaching listeners to SVG elements at render time, Mermaid enables developers to execute custom logic—such as opening modals, triggering API calls, or navigating between views—when users interact with specific nodes.
Understanding the Click Handler Architecture
Mermaid’s event system separates concerns across three distinct phases, moving from syntax parsing to runtime execution.
Phase 1: Parsing the Click Directive
During the initial parsing stage, the Flowchart parser identifies lines beginning with the click keyword and extracts three components: the target node identifier, the callback function name, and an optional tooltip text. This metadata is stored in the diagram’s internal model for subsequent rendering operations.
According to the source code in src/diagrams/flowchart/parser/flowchart.jison, the parser grammar recognizes the click statement and populates the diagram data structure with the callback reference before the SVG generation phase begins.
Phase 2: Attaching Handlers During Rendering
When the SVG renderer processes the parsed model, it generates DOM elements for each node—typically wrapping shapes in <g> elements or rendering them as <rect> elements. If the internal model contains click metadata for a node, the renderer attaches an event listener directly to that SVG element.
As implemented in src/renderer/svgRenderer.js, the listener resolves the named callback by looking up the function on the global window.mermaid object (or a custom namespace you provide) and invokes it with the node’s ID as the sole argument.
Phase 3: Event Dispatch Through the Global API
At runtime, the Mermaid API exposed in src/mermaidAPI.js facilitates the callback resolution mechanism. When a user clicks a node, the attached listener executes and dispatches the event to your application code. The system also automatically injects an SVG <title> element containing the optional tooltip text specified in the diagram syntax, enabling native browser hover behavior without additional JavaScript.
Basic Implementation Example
Define your diagram using the click directive syntax, then expose the callback function on the global window.mermaid object.
graph TD
A[Start] --> B{Is it ok?}
B -->|Yes| C[Proceed]
B -->|No| D[Abort]
click B onNodeClick "Show details for B"
click C onNodeClick "Show details for C"
// Ensure the callback is globally reachable under the mermaid namespace
window.mermaid = window.mermaid || {}
window.mermaid.onNodeClick = function (nodeId) {
// nodeId corresponds to the identifier in the diagram (e.g., "B" or "C")
console.log('Node clicked:', nodeId)
// Example: open a modal with node-specific information
const modal = document.getElementById('info-modal')
modal.querySelector('.modal-body').textContent = `Details for node ${nodeId}`
modal.style.display = 'block'
}
// Initialize and render
mermaid.initialize({ startOnLoad: false })
mermaid.contentLoaded()
Configuring Custom Namespaces
For applications that avoid global namespace pollution, you can bind click handlers to custom objects. However, you must set securityLevel: 'loose' in the configuration to allow Mermaid to resolve functions outside its sandbox.
graph LR
X[Item X] --> Y[Item Y]
click X myApp.handlers.handleClick "Handle X"
click Y myApp.handlers.handleClick "Handle Y"
const myApp = {
handlers: {
handleClick: function (nodeId) {
alert(`You clicked ${nodeId}`)
}
}
}
// Configure Mermaid to allow external function calls
mermaid.initialize({
startOnLoad: false,
securityLevel: 'loose'
})
document.addEventListener('DOMContentLoaded', () => {
// Expose custom object under the global mermaid namespace
window.mermaid = myApp
mermaid.contentLoaded()
})
Dynamically Updating Node Tooltips
The renderer creates an SVG <title> element for each node that includes a click handler, using the tooltip text provided in the diagram syntax. You can programmatically update this tooltip after rendering by selecting the title element within the node’s DOM structure.
function updateTooltip(nodeId, newText) {
const selector = `#${nodeId} title`
const titleElement = document.querySelector(selector)
if (titleElement) {
titleElement.textContent = newText
}
}
// Update tooltip on click to show timestamp
window.mermaid.onNodeClick = function (nodeId) {
updateTooltip(nodeId, `Clicked at ${new Date().toLocaleTimeString()}`)
}
Summary
- Parse phase: The
clickdirective is parsed insrc/diagrams/flowchart/parser/flowchart.jison, storing the callback name and tooltip in the diagram model. - Render phase: The SVG renderer in
src/renderer/svgRenderer.jsattaches click listeners to node elements that resolve callbacks on the global scope. - Global resolution: Callbacks must be reachable on
window.mermaidor a custom object exposed there, requiringsecurityLevel: 'loose'for non-global functions. - Tooltip support: Optional tooltip text is rendered as a native SVG
<title>element for hover visibility. - Entry point: Use
mermaid.contentLoaded()frompackages/mermaid/src/index.jsto trigger rendering after configuring your handlers.
Frequently Asked Questions
Where does Mermaid look for the callback function when a node is clicked?
Mermaid resolves the callback by looking up the function name specified in the click directive on the global window.mermaid object. As implemented in src/renderer/svgRenderer.js, the event listener performs this lookup at click time and invokes the function with the node ID as the only parameter. If you use a custom namespace, you must assign that object to window.mermaid before rendering.
Can I use click handlers with untrusted diagram content?
No. To execute arbitrary JavaScript callbacks from diagram syntax, you must set securityLevel: 'loose' in the Mermaid configuration. The default security settings restrict function execution to prevent XSS attacks. Only use click handlers with diagram definitions you trust, as the loose setting allows the renderer to evaluate and call functions from the parsed model.
How do I remove or disable a click handler after the diagram renders?
Since Mermaid attaches standard DOM event listeners during the rendering phase in src/renderer/svgRenderer.js, you can remove handlers using standard JavaScript methods. Select the SVG element by its node ID and call removeEventListener, or replace the callback function on window.mermaid with a no-op function to disable interaction while preserving the diagram structure.
Which diagram types support the click directive?
The analysis of src/diagrams/flowchart/parser/flowchart.jison confirms that the Flowchart diagram type explicitly supports the click directive. While the general rendering pipeline in src/renderer/svgRenderer.js is diagram-agnostic, the parsing logic must specifically recognize the click keyword. Check individual diagram parsers in the src/diagrams/ directory to confirm support for other diagram types like Sequence or Gantt.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →