HTML context menu remains on the screen

Hi,
We use native HTML when implementing context menu for all elements including diagram.
If i user right click on the diagram, the context menu is show, but, then, if he moves the mouse OUTSIDE the diagram and click elsewhere on the screen, the context menu retains on the screen.
The context menu disappears only when:

  1. The user selects one of the options.
  2. The user clicks elsewhere on the diagram.

What can be done ?
Regards,
Tany

Implement a “LostFocus” DiagramEvent listener that cancels the tool. This will work for GoJS context menus:

    $(go.Diagram, "myDiagramDiv",
      {
        "LostFocus": function(e) {
          if (e.diagram.currentTool instanceof go.ContextMenuTool) {
            e.diagram.currentTool.doCancel();
          }
        },
      . . .

Great !!! Works !!!
I didn’t see this attribute in Diagram model.
Is it an undocumented feature ?

It’s documented: https://gojs.net/latest/intro/events.html#LostFocus and https://gojs.net/latest/api/symbols/DiagramEvent.html.

Huston, we…
Now that i added the code to my diagram,
any menu selection is disregarded and the menu became useless.

I have put a break point at the lostFocus function.
When the user selects a menu item, the function is fired before the function that implements the menu item.

I’m not sure about a good solution for this situation. We’ll investigate it more on Monday.

OK, here’s a partial solution that Simon came up with. Move that hiding code to a separate function:

      function hideCX() {
        if (myDiagram.currentTool instanceof go.ContextMenuTool) {
          myDiagram.currentTool.doCancel();
        }
      }

Then in your showContextMenu function (that’s the name in the samples/customContextMenu.html` sample, but could be anything in your code) where you are showing the HTML for the context menu, add this:

      function showContextMenu(obj, diagram, tool) {
        . . .
        // Optional: Use a `window` click listener with event capture to
        //           remove the context menu if the user clicks elsewhere on the page
        window.addEventListener("click", hideCX, true);
      }

Then clean up that listener when hiding the context menu:

      function hideContextMenu() {
        cxElement.classList.remove("show-menu");
        // Optional: Use a `window` click listener with event capture to
        //           remove the context menu if the user clicks elsewhere on the page
        window.removeEventListener("click", hideCX, true);
      }

This should handle clicks anywhere else on your page, but not when changing focus to another window.

Looks good,
Thanks