Disabling context menu on chart

Normally, browsers will display a context menu when you press right mouse button over some element. If done over amCharts 5, it will display a context menu for a <canvas> element. This tutorial will show how you can disable default behavior of a right-click on canvas elements, as well as attach built-in rightclick event to apply your own logic.

Disabling built-in context menu

To disable default context menu, we'll need to cancel contextmenu event, on the <div> root element is placed in:

root.dom.addEventListener("contextmenu", function(ev) {
  ev.preventDefault();
});
root.dom.addEventListener("contextmenu", function(ev) {
  ev.preventDefault();
});

Or we can use amCharts 5' built-in utility, which returns a Disposer:

am5.utils.addEventListener(root.dom, "contextmenu", function(ev) {
  ev.preventDefault();
});
am5.utils.addEventListener(root.dom, "contextmenu", function(ev) {
  ev.preventDefault();
});

And to be completely on the safe side, we can add that disposer to root element disposer list, so when root element is disposed, the event handler goes with it:

root.addDisposer(
  am5.utils.addEventListener(root.dom, "contextmenu", function(ev) {
    ev.preventDefault();
  })
);
root.addDisposer(
  am5.utils.addEventListener(root.dom, "contextmenu", function(ev) {
    ev.preventDefault();
  })
);

Adding right-click event

With built-in context menu out of the way, we can add amCharts rightclick event on the target elements.

The following code adds one to Force-directed tree nodes:

series.nodes.template.events.on("rightclick", function(ev) {
  console.log("Right click")
});
series.nodes.template.events.on("rightclick", function(ev) {
  console.log("Right click")
});

See the Pen amCharts 5: Disabling built-in context menu by amCharts team (@amcharts) on CodePen.

Posted in Uncategorized