3

I'm trying to render dynamic charts and therefore need to use the mermaid.render function. But using click does not work when the code isn't entered in a static way as you can see in the snippet bellow:

<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>

<script>
  mermaid.initialize({
    theme: "base",
    startOnLoad: false,
    securityLevel: 'loose'
  });
</script>

<p onclick="CreateGraph()">CreateGraph</p>
<div class="mermaid"></div>

<script>
  var CreateGraph = function() {
    var gdata = `
            flowchart 
             a-->b
             click a callback
            `;
    var div = document.getElementsByClassName("mermaid")[0];
    mermaid.render("graphDiv", gdata, (svgCode, bindFunctions) => {
      div.innerHTML = svgCode;
    });
  };
  var callback = function() {
    alert('A callback was triggered');
  };
</script>

But if you were to put the content of gdata and put directly inside the mermaid div (as well as setting startOnLoad to true) then everything would work as expected.

Does anyone have a clue on what's happening or maybe a fix?

Thank you!

eriv
  • 133
  • 3

2 Answers2

3

Alternative. Use href to include the function call in the parameter.

var gdata = `
            flowchart 
             a-->b
             click a href "javascript:callback();"
            `; 
Majjin
  • 46
  • 2
  • This is some galaxy brain tip. Maybe the only option when you have dynamic graphs. Learned the hard way that binds and tooltips dont work with graphs generated by the render function – Rafael Palliarini Dec 21 '22 at 23:15
1

For the click events to work, after updating the innerHTML of the element you must also set the bindFunctions.

   element = document.querySelector('#some_id');

   const insertSvg = function (svgCode, bindFunctions) {
      element.innerHTML = svgCode;
      bindFunctions(element);
   };

   const graphDefinition = 'graph TB\na-->b';
   // Render the graph
   const graph = await mermaid.mermaidAPI.render('graphDiv', graphDefinition, insertSvg);