# How to Implement Click Handlers on Nodes in Mermaid Diagrams

> Learn to implement click handlers on Mermaid diagram nodes. Use the click directive to link nodes to JavaScript functions for interactive diagrams. Enhance your Mermaid workflows today.

- Repository: [mermaid-js/mermaid](https://github.com/mermaid-js/mermaid)
- Tags: how-to-guide
- Published: 2026-02-23

---

**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`](https://github.com/mermaid-js/mermaid/blob/main/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`](https://github.com/mermaid-js/mermaid/blob/main/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.

```mermaid
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"

```

```javascript
// 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.

```mermaid
graph LR
    X[Item X] --> Y[Item Y]
    click X myApp.handlers.handleClick "Handle X"
    click Y myApp.handlers.handleClick "Handle Y"

```

```javascript
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.

```javascript
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 `click` directive is parsed in `src/diagrams/flowchart/parser/flowchart.jison`, storing the callback name and tooltip in the diagram model.
- **Render phase**: The SVG renderer in [`src/renderer/svgRenderer.js`](https://github.com/mermaid-js/mermaid/blob/main/src/renderer/svgRenderer.js) attaches click listeners to node elements that resolve callbacks on the global scope.
- **Global resolution**: Callbacks must be reachable on `window.mermaid` or a custom object exposed there, requiring `securityLevel: '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()` from [`packages/mermaid/src/index.js`](https://github.com/mermaid-js/mermaid/blob/main/packages/mermaid/src/index.js) to 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`](https://github.com/mermaid-js/mermaid/blob/main/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`](https://github.com/mermaid-js/mermaid/blob/main/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`](https://github.com/mermaid-js/mermaid/blob/main/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.